import { execute, insertMany, query, type Db, type Row } from "../../core/db/db.js";
import { today } from "../../shared/dates.js";
import { computable, computeIndicator, type ProviderInputs } from "./kpi.rules.js";

export async function loadInputs(db: Db, projectId: string): Promise<ProviderInputs[]> {
  const base = await query(db, `SELECT p.id, COALESCE((SELECT c.target_trainees FROM provider_contracts c WHERE c.provider_id=p.id AND c.status IN ('active','amended') ORDER BY c.status='active' DESC, c.id DESC LIMIT 1),0) AS target,
      COUNT(s.trainee_id) AS registered, SUM(s.eligibility_status='eligible') AS eligible, SUM(s.att_present_to_date) AS present, SUM(s.att_sessions_to_date) AS possible,
      SUM(s.dropout_status='yes' OR s.system_dropout_final) AS effectiveDropouts, SUM(s.completion_status='yes') AS completers, SUM(s.certification_status='yes') AS certified, SUM(s.placement_status='yes') AS placed,
      SUM(s.locality_status='yes') AS locality, SUM(s.retention_3m_status='yes') AS retained
    FROM providers p LEFT JOIN trainee_status s ON s.provider_id=p.id AND s.roster_status IN ('active','reserve') WHERE p.project_id=? GROUP BY p.id ORDER BY p.code`, [projectId]);
  // Attendance capture: every tracked trainee needs a mark on every counted day so far.
  const capture = await query(db, `SELECT s.provider_id AS id, SUM(s.att_sessions_to_date) AS expected FROM trainee_status s WHERE s.project_id=? AND s.roster_status IN ('active','reserve') GROUP BY s.provider_id`, [projectId]);
  const marks = await query(db, `SELECT s.provider_id AS id, SUM(s.att_marks) AS n FROM trainee_status s WHERE s.project_id=? AND s.roster_status IN ('active','reserve') GROUP BY s.provider_id`, [projectId]);
  const griev = await query(db, `SELECT provider_id AS id, SUM(first_response_at IS NOT NULL AND first_response_at<=due_at) AS timely, SUM(first_response_at IS NOT NULL OR due_at<UTC_TIMESTAMP(3)) AS due FROM grievance_cases WHERE project_id=? GROUP BY provider_id`, [projectId]);
  const rep = await query(db, `SELECT DISTINCT r.provider_id AS id, r.report_type AS type FROM outcome_reports r JOIN outcome_report_lines l ON l.report_id=r.id JOIN trainees t ON t.id=l.trainee_id WHERE r.project_id=? AND r.status='accepted' AND t.roster_status IN ('active','reserve')`, [projectId]);
  const acts = await query(db, "SELECT o.provider_id AS id, d.code, SUM(o.status IN ('submitted','approved')) AS s FROM activity_obligations o JOIN activity_definitions d ON d.id=o.definition_id WHERE o.project_id=? GROUP BY o.provider_id, d.code", [projectId]);
  const get = (rows: Row[], id: string) => rows.find((r) => r["id"] === id) ?? {};
  return base.map((b) => ({
    ...Object.fromEntries(Object.entries(b).map(([k, v]) => [k, k === "id" ? v : Number(v ?? 0)])),
    captureExpected: Number(get(capture, b["id"])["expected"] ?? 0), captureSubmitted: Number(get(marks, b["id"])["n"] ?? 0), timely: Number(get(griev, b["id"])["timely"] ?? 0), due: Number(get(griev, b["id"])["due"] ?? 0),
    activities: new Map(acts.filter((x) => x["id"] === b["id"]).map((x) => [String(x["code"]), { submitted: Number(x["s"]) }])),
    reported: new Set(rep.filter((r) => r["id"] === b["id"]).map((r) => String(r["type"]))),
  })) as unknown as ProviderInputs[];
}
export const resolveTargets = (db: Db, projectId: string, asOf: string) => query(db, `SELECT indicator_code AS code, provider_id AS providerId, target_value AS value, comparator FROM indicator_targets
  WHERE project_id=? AND effective_from<=? AND (effective_to IS NULL OR effective_to>=?) ORDER BY effective_from, id`, [projectId, asOf, asOf]);

/** Verified layer: the latest finalised run per provider, highest tier first (V1 rule). */
async function verified(db: Db, projectId: string, code: string): Promise<{ id: string; n: number; d: number }[]> {
  // With stages (30 and 60 days), the last one decides (V1 rule).
  const stage = (await query(db, "SELECT stage_key AS k FROM indicator_stages WHERE project_id=? AND indicator_code=? AND is_active=1 ORDER BY is_final DESC, sort_order DESC, id DESC LIMIT 1", [projectId, code]))[0]?.["k"] as string | undefined;
  const runs = await query(db, "SELECT id, provider_id AS p, cnt_success AS n, cnt_definite AS d, parent_run_id AS parent FROM verification_runs WHERE project_id=? AND indicator_code=? AND status='finalised' AND (? IS NULL OR stage_key=?) ORDER BY tier DESC, drawn_at DESC, id DESC", [projectId, code, stage ?? null, stage ?? null]);
  const seen = new Map<string, { id: string; n: number; d: number }>();
  for (const r of runs) if (!seen.has(r["p"])) {
    const parent = r["parent"] ? runs.find((x) => x["id"] === r["parent"]) : undefined;
    seen.set(r["p"], { id: String(r["p"]), n: r["n"] + (parent?.["n"] ?? 0), d: r["d"] + (parent?.["d"] ?? 0) });
  }
  return [...seen.values()];
}
export async function recomputeKpis(db: Db, projectId: string, asOf = today()): Promise<number> {
  const inputs = await loadInputs(db, projectId);
  const defs = await query(db, "SELECT code, numerator_metric AS nm, denominator_metric AS dm, version_no AS v, direction, comparator, default_target AS t, verification_method AS vm FROM indicator_definitions WHERE project_id=? AND status='active'", [projectId]);
  const targets = await resolveTargets(db, projectId, asOf);
  const rows: (string | number | null)[][] = [];
  for (const def of defs) {
    const formula = { numerator: String(def["nm"]), denominator: (def["dm"] as string) ?? null };
    if (!computable(formula)) continue;
    const result = computeIndicator(formula, inputs)!;
    const push = (provider: string, layer: string, n: number | null, d: number | null, value: number | null, none: boolean) => {
      const own = targets.filter((t) => t["code"] === def["code"] && t["providerId"] === provider).at(-1), project = targets.filter((t) => t["code"] === def["code"] && t["providerId"] === null).at(-1);
      const target = own ?? project, tv = target ? Number(target["value"]) : provider && String(def["nm"]).startsWith("provider.") ? 1 : def["t"];
      const met = none ? "no_data" : tv === null ? "not_applicable" : (target?.["comparator"] ?? def["comparator"]) === "<=" ? (value! <= tv ? "met" : "not_met") : value! >= tv ? "met" : "not_met";
      rows.push([projectId, def["code"], layer, provider || "0", "", asOf, def["v"], n, d, none ? null : value, tv, own ? "provider" : project ? "project_default" : def["t"] !== null ? "definition" : "none", met]);
    };
    for (const p of inputs) { const f = result.byProvider.get(p.id)!; push(p.id, "monitoring", f.numerator, f.denominator, f.value, f.denominator === 0); }
    push("", "monitoring", result.project.numerator, result.project.denominator, result.project.value, result.project.denominator === 0);
    if (def["vm"] === "sampling") {
      const v = await verified(db, projectId, def["code"]);
      for (const x of v) push(x.id, "verified", x.n, x.d, x.d ? Math.round((x.n / x.d) * 10000) / 100 : 0, x.d === 0);
      const n = v.reduce((a, x) => a + x.n, 0), d = v.reduce((a, x) => a + x.d, 0);
      if (v.length) push("", "verified", n, d, d ? Math.round((n / d) * 10000) / 100 : 0, d === 0);
    }
  }
  await execute(db, "DELETE FROM kpi_snapshots WHERE project_id=? AND as_of_date=?", [projectId, asOf]);
  if (rows.length) await insertMany(db, "kpi_snapshots", ["project_id", "indicator_code", "layer", "provider_key", "dimension_key", "as_of_date", "definition_version", "numerator", "denominator", "value", "target_value", "target_source", "status", "computed_at"], rows.map((r) => [...r, new Date().toISOString().slice(0, 23).replace("T", " ")]));
  return rows.length;
}
