import { readFileSync } from "node:fs";
import { join } from "node:path";
import type { Connection, RowDataPacket } from "mysql2/promise";
import { splitSql } from "./split-sql.js";

export interface Check { name: string; v1: string; v2: string; ok: boolean }

/** Columns that must hold exactly the V1 value (compared per row, NULL-safe). [V2 table, V1 table, [V2 column, V1 expression][]] */
const VALUES: [string, string, [string, string][]][] = [
  ["users", "users", [["name", "s.name"], ["password_hash", "s.password"], ["must_change_password", "s.must_change_password"]]],
  ["providers", "training_providers", [["code", "s.tp_code"], ["name", "s.name"], ["contact_phone_raw", "s.contact_phone"]]],
  ["provider_contracts", "training_provider_contracts", [["target_trainees", "s.contract_target"], ["effective_from", "s.effective_from"]]],
  ["trainings", "trainings", [["title", "s.title"], ["provider_id", "s.training_provider_id"], ["planned_start", "DATE(s.start_date)"], ["planned_end", "DATE(s.end_date)"]]],
  ["training_classes", "training_batches", [["code", "s.code"], ["name", "s.name"], ["site_id", "s.cohort_id"], ["planned_start", "DATE(s.start_date)"], ["effective_end", "DATE(s.end_date)"], ["actual_start", "DATE(s.timeline_anchor_date)"]]],
  ["trainees", "trainees", [["trainee_code", "s.trainee_unique_id"], ["provider_id", "s.training_provider_id"], ["class_id", "s.batch_id"], ["site_id", "s.cohort_id"],
    ["first_name", "TRIM(s.first_name)"], ["father_name", "NULLIF(TRIM(s.father_name),'')"], ["grandfather_name", "NULLIF(TRIM(s.grandfather_name),'')"], ["sex_raw", "s.sex"], ["age_years", "s.age_years"], ["dob_raw", "s.date_of_birth_et_calendar"],
    ["form_completion_date", "DATE(s.date_of_form_completion)"], ["phone_raw", "s.phone_primary"], ["phone_alt_raw", "s.phone_alternative"], ["region_raw", "s.region"], ["education_raw", "s.highest_education"],
    ["employment_raw", "s.employment_status"], ["skill_usage_raw", "s.skill_usage"], ["plan_raw", "s.post_training_employment_plan_type"], ["disability_raw", "s.disability_type"], ["is_pwd", "s.disability_flag"],
    ["is_idp", "s.idp_flag"], ["is_returnee", "s.returnee_flag"], ["is_low_income", "s.low_income_flag"], ["income_sufficient", "s.income_sufficient"], ["previously_participated", "s.previously_participated"],
    ["consent_accuracy", "s.consent_accuracy"], ["consent_followup", "s.consent_followup_surveys"], ["consent_contact_verify", "s.consent_contact_verify"], ["consent_image_use", "s.consent_image_use"],
    ["emergency_phone_raw", "s.emergency_contact_phone"], ["raw_payload", "s.raw_payload"], ["legacy_roster_role", "s.roster_role"], ["attendance_eligible_from", "s.attendance_eligible_from"], ["created_at", "s.created_at"]]],
  ["outcome_report_lines", "trainee_outcomes", [["trainee_id", "s.trainee_id"], ["report_id", "s.report_batch_id"], ["value", "IF(s.reported_value=1,'yes','no')"], ["raw_json", "s.meta"], ["legacy_status_date", "s.status_date"]]],
  ["verification_subjects", "verification_sample_subjects", [["trainee_id", "s.trainee_id"], ["status_code", "s.verification_status_code"], ["verified_value", "s.verified_value"], ["tp_claim_value", "s.tp_claim_value"], ["reviewer_note", "s.reviewer_note"]]],
  ["grievance_cases", "feedback_threads", [["ref", "s.ref_code"], ["subject", "s.subject"], ["description", "s.description"], ["submitted_at", "s.submitted_at"], ["due_at", "s.due_at"], ["resolved_at", "s.resolved_at"]]],
  ["grievance_messages", "feedback_messages", [["case_id", "s.thread_id"], ["body", "s.body"], ["created_at", "s.created_at"]]],
];

export async function reconcile(db: Connection): Promise<Check[]> {
  await db.query("USE pbps_v2");
  const checks: Check[] = [];
  for (const statement of splitSql(readFileSync(join(import.meta.dirname, "reconcile.sql"), "utf8"))) {
    const [rows] = await db.query(statement);
    if (/^SELECT/i.test(statement) && Array.isArray(rows)) for (const r of rows as RowDataPacket[]) if ("check_name" in r) checks.push({ name: String(r["check_name"]), v1: String(r["v1"]), v2: String(r["v2"]), ok: r["v1"] !== null && String(r["v1"]) === String(r["v2"]) });
    // Queries without a check_name list differences: any row is a failure.
    if (/^SELECT/i.test(statement) && Array.isArray(rows) && !statement.includes("FROM recon")) checks.push({ name: `no differences: ${statement.slice(0, 70).replace(/\s+/g, " ")}`, v1: "0", v2: String(rows.length), ok: rows.length === 0 });
  }
  const count = async (sql: string) => { const [r] = await db.query<RowDataPacket[]>(sql); return Number(r[0]!["n"]); };
  for (const [v2, v1, columns] of VALUES) for (const [column, expr] of columns) {
    const different = await count(`SELECT COUNT(*) n FROM pbps_mis.${v1} s LEFT JOIN ${v2} v ON v.id = s.id WHERE v.id IS NULL OR NOT (${column.endsWith("_at") ? `v.${column} <=> ${expr}` : `BINARY v.${column} <=> BINARY (${expr})`})`);
    checks.push({ name: `value ${v2}.${column}: rows that differ`, v1: "0", v2: String(different), ok: different === 0 });
  }
  const marks = await count(`SELECT COUNT(*) n FROM pbps_mis.trainee_attendance_days a LEFT JOIN attendance_sessions s ON s.class_id=a.batch_id AND s.session_date=a.session_date
    LEFT JOIN attendance_marks m ON m.session_id=s.id AND m.trainee_id=a.trainee_id WHERE NOT (m.status <=> (CASE a.status WHEN 'present' THEN 1 WHEN 'absent' THEN 2 WHEN 'excused' THEN 3 END)) OR m.status IS NULL`);
  checks.push({ name: "value attendance: every mark equal to V1", v1: "0", v2: String(marks), ok: marks === 0 });
  const homeless = await count("SELECT COUNT(*) n FROM activity_submissions WHERE obligation_id IS NULL");
  checks.push({ name: "every activity submission belongs to an obligation", v1: "0", v2: String(homeless), ok: homeless === 0 });
  const unknownStatus = await count("SELECT COUNT(*) n FROM trainee_status WHERE dropout_status='yes' AND (completion_status='pending' OR certification_status='pending' OR placement_status='pending' OR locality_status='pending' OR retention_3m_status='pending')");
  checks.push({ name: "every dropout has a known status up to the last indicator", v1: "0", v2: String(unknownStatus), ok: unknownStatus === 0 });
  const gap = await count("SELECT COUNT(*) n FROM outcome_reports r JOIN trainee_status s ON s.class_id=r.class_id AND s.dropout_status='yes' AND s.roster_status IN ('active','reserve') WHERE r.status='accepted' AND r.report_type<>'dropout' AND NOT EXISTS (SELECT 1 FROM outcome_report_lines l JOIN outcome_reports o ON o.id=l.report_id WHERE o.class_id=r.class_id AND o.report_type=r.report_type AND o.status='accepted' AND l.trainee_id=s.trainee_id)");
  checks.push({ name: "every reported dropout has a line in every submitted report of the class", v1: "0", v2: String(gap), ok: gap === 0 });
  const unknown = await count("SELECT COUNT(*) n FROM indicator_definitions WHERE status='active' AND (numerator_metric LIKE 'unknown:%' OR denominator_metric LIKE 'unknown:%')");
  checks.push({ name: "every active indicator is built from variables V2 can calculate", v1: "0", v2: String(unknown), ok: unknown === 0 });
  const computed = await count("SELECT COUNT(*) n FROM indicator_definitions d WHERE d.status='active' AND NOT EXISTS (SELECT 1 FROM kpi_snapshots k WHERE k.project_id=d.project_id AND k.indicator_code=d.code AND k.layer='monitoring' AND k.provider_key=0)");
  checks.push({ name: "every active indicator has a calculated value row", v1: "0", v2: String(computed), ok: computed === 0 });
  const protocol = await count("SELECT COUNT(*) n FROM indicator_definitions WHERE status='active' AND protocol_no BETWEEN 1 AND 18 AND operational_definition<>''");
  checks.push({ name: "all 18 protocol indicators have their definition (job linkage and decent job are one)", v1: "18", v2: String(protocol), ok: protocol >= 18 });
  const target = await count("SELECT COUNT(*) n FROM verification_runs r JOIN pbps_mis.verification_sample_runs s ON s.id=r.id JOIN pbps_mis.project_indicators i ON i.id=s.indicator_id WHERE NOT (r.target_used <=> COALESCE(i.threshold_value, 90))");
  checks.push({ name: "every verification run has V1's target", v1: "0", v2: String(target), ok: target === 0 });
  const files = await count("SELECT COUNT(*) n FROM files WHERE legacy_path IS NOT NULL");
  const stored = await count("SELECT COUNT(*) n FROM files WHERE legacy_path IS NOT NULL AND sha256 IS NOT NULL AND sha256 <> ''");
  checks.push({ name: "evidence files copied with checksum", v1: String(files), v2: String(stored), ok: files === stored });
  return checks;
}
