#!/usr/bin/env bash

report_count_from_file() {
  local file_path="$1"
  local key="$2"

  if [[ ! -f "$file_path" ]]; then
    printf '0\n'
    return
  fi

  awk -F: -v key="$key" '$1 == key {print $2; found=1; exit} END {if (!found) print "0"}' "$file_path"
}

report_first_count() {
  local key="$1"
  shift

  local file_path
  local count

  for file_path in "$@"; do
    count="$(report_count_from_file "$file_path" "$key")"
    if [[ "$count" != "0" ]]; then
      printf '%s\n' "$count"
      return
    fi
  done

  printf '0\n'
}

write_backup_markdown_report() {
  local backup_dir="$1"
  local status="$2"
  local services="$3"
  local timings_json="${4:-[]}"
  local reports_dir="$backup_dir/reports"
  local output_file="$reports_dir/backup-report.md"
  local created_at
  local manifest_created_at="unknown"
  local git_commit="unknown"
  local users
  local tenants
  local relying_parties
  local rp_user_custom_claims
  local global_custom_claim_users
  local hydra_clients
  local works_org_units
  local works_users
  local timings_table

  mkdir -p "$reports_dir"
  created_at="$(backup_utc_now)"

  if [[ -f "$backup_dir/manifest.json" ]]; then
    manifest_created_at="$(jq -r '.created_at // "unknown"' "$backup_dir/manifest.json")"
    git_commit="$(jq -r '.git_commit // "unknown"' "$backup_dir/manifest.json")"
  fi

  users="$(report_first_count "public.users" "$reports_dir/baron-postgres-row-counts.txt")"
  tenants="$(report_first_count "public.tenants" "$reports_dir/baron-postgres-row-counts.txt")"
  relying_parties="$(report_first_count "public.relying_parties" "$reports_dir/baron-postgres-row-counts.txt")"
  rp_user_custom_claims="$(report_first_count "public.rp_user_metadata" "$reports_dir/baron-postgres-custom-claim-counts.txt" "$reports_dir/baron-postgres-row-counts.txt")"
  global_custom_claim_users="$(report_first_count "public.users.global_custom_claims" "$reports_dir/baron-postgres-custom-claim-counts.txt")"
  hydra_clients="$(report_first_count "public.hydra_client" "$reports_dir/ory_hydra-row-counts.txt")"
  works_org_units="$(report_first_count "public.works_org_units" "$reports_dir/baron-postgres-row-counts.txt")"
  works_users="$(report_first_count "public.works_users" "$reports_dir/baron-postgres-row-counts.txt")"

  timings_table="$(jq -r '
    if type != "array" or length == 0 then
      "| 없음 | 0 |"
    else
      .[] | "| \(.service) | \(.duration_seconds) |"
    end
  ' <<<"$timings_json")"

  {
    printf '# Baron SSO Backup Report\n\n'
    printf '| 항목 | 값 |\n'
    printf '| --- | --- |\n'
    printf '| 생성 시각 | %s |\n' "$created_at"
    printf '| 백업 시각 | %s |\n' "$manifest_created_at"
    printf '| 상태 | %s |\n' "$status"
    printf '| 백업 경로 | `%s` |\n' "$backup_dir"
    printf '| Git Commit | `%s` |\n' "$git_commit"
    printf '| 서비스 | `%s` |\n\n' "$services"
    printf '## 요약\n\n'
    printf '| 지표 | 값 |\n'
    printf '| --- | ---: |\n'
    printf '| 사용자 | %s |\n' "$users"
    printf '| 테넌트 | %s |\n' "$tenants"
    printf '| RP | %s |\n' "$relying_parties"
    printf '| RP 사용자 custom claim | %s |\n' "$rp_user_custom_claims"
    printf '| 전역 custom claim 사용자 | %s |\n' "$global_custom_claim_users"
    printf '| Hydra Client | %s |\n' "$hydra_clients"
    printf '| WORKS 조직 | %s |\n' "$works_org_units"
    printf '| WORKS 사용자 | %s |\n\n' "$works_users"
    printf '## 서비스별 수행 시간\n\n'
    printf '| 서비스 | 초 |\n'
    printf '| --- | ---: |\n'
    printf '%s\n' "$timings_table"
  } >"$output_file"
}

write_restore_markdown_report() {
  local restore_json="$1"
  local output_file

  [[ -f "$restore_json" ]] || return 0
  output_file="${restore_json%.json}.md"

  jq -r '
    def services: (.services // [] | join(", "));
    def verification_rows:
      (.verification.target_reports // []) as $reports
      | if ($reports | length) == 0 then
          "| 없음 | not_run |  |"
        else
          $reports[]
          | "| \(.service) | \(.status) | \(.diff_file // "") |"
        end;
    "# Baron SSO Restore Report\n",
    "| 항목 | 값 |",
    "| --- | --- |",
    "| 시작 시각 | \(.started_at // "unknown") |",
    "| 종료 시각 | \(.finished_at // "unknown") |",
    "| 상태 | \(.status // "unknown") |",
    "| 메시지 | \(.message // "") |",
    "| 입력 유형 | \(.backup_source // "unknown") |",
    "| 백업 경로 | `\(.backup_dir // "")` |",
    "| Dump 파일 | `\(.dump_file // "")` |",
    "| 서비스 | `\(services)` |",
    "",
    "## 검증",
    "",
    "| 항목 | 상태 |",
    "| --- | --- |",
    "| Dump checksum | \(.verification.dump_checksum // "not_run") |",
    "| 대상 row count | \(.verification.target_row_counts // "not_run") |",
    "",
    "## 대상별 검증 결과",
    "",
    "| 서비스 | 상태 | Diff |",
    "| --- | --- | --- |",
    verification_rows
  ' "$restore_json" >"$output_file"
}
