import { audit } from "../../core/audit/audit.js";
import { execute, insert, json, one, pool, query, transaction, type Row } from "../../core/db/db.js";
import { enqueue } from "../../core/jobs/jobs.js";
import { conflict, invalid, notFound, type Ctx } from "../../core/http/route.js";
import { addDays, today } from "../../shared/dates.js";
import { queueKpis } from "../projects/index.js";
import { METRICS, metricOf } from "./kpi.rules.js";
import { loadInputs, resolveTargets } from "./kpi.service.js";

const view = (d: Row) => ({ id: d["id"], code: d["code"], no: d["protocol_no"] ?? 0, name: d["name"], level: d["level"], purpose: d["purpose"] === "monitoring_and_verification" ? "both" : d["purpose"], unit: d["unit"] === "count" ? "#" : "%", direction: d["direction"], defaultTarget: Number(d["default_target"] ?? 0), verificationMethod: d["verification_method"], definition: d["operational_definition"] ?? d["name"], numerator: d["numerator_metric"], denominator: d["denominator_metric"] ?? "" });
export const definitions = (pid: string) => query(pool, "SELECT * FROM indicator_definitions WHERE project_id=? AND status='active' ORDER BY COALESCE(protocol_no,99), display_order", [pid]);
const latestDate = async (pid: string, asOf = today()): Promise<string | null> => (await one(pool, "SELECT MAX(as_of_date) AS d FROM kpi_snapshots WHERE project_id=? AND as_of_date<=?", [pid, asOf]))?.["d"] ?? null;
export const snapshot = async (pid: string, asOf?: string): Promise<Row[]> => { const d = await latestDate(pid, asOf); return d ? query(pool, "SELECT * FROM kpi_snapshots WHERE project_id=? AND as_of_date=?", [pid, d]) : []; };
const num = (v: unknown) => (v === null || v === undefined ? undefined : Number(v));
export function value(rows: Row[], code: string, providerId: string | null) {
  const pick = (layer: string) => rows.find((r) => r["indicator_code"] === code && r["layer"] === layer && String(r["provider_key"]) === (providerId ?? "0")), r = pick("monitoring"), v = pick("verified");
  return { indicatorCode: code, ...(providerId ? { providerId } : {}), layer: "monitoring" as const, value: num(r?.["value"]), numerator: num(r?.["numerator"]), denominator: num(r?.["denominator"]), target: num(r?.["target_value"]), targetSource: r?.["target_source"] ?? "none", status: r?.["status"] ?? "no_data", asOf: r?.["as_of_date"] ?? today(), computedAt: r?.["computed_at"] ?? new Date().toISOString(), ...(v?.["value"] !== undefined && v["value"] !== null ? { verified: Number(v["value"]) } : {}) };
}
export async function cards(pid: string, providerId: string | null, codes?: string[]) {
  const rows = await snapshot(pid), defs = await definitions(pid), trend = await query(pool, "SELECT indicator_code AS c, as_of_date AS date, value FROM kpi_snapshots WHERE project_id=? AND layer='monitoring' AND provider_key=? AND as_of_date>=? ORDER BY as_of_date", [pid, providerId ?? "0", addDays(today(), -90)]);
  return defs.filter((d) => !codes || codes.includes(d["code"])).map((d) => { const t = trend.filter((x) => x["c"] === d["code"] && x["value"] !== null).map((x) => ({ date: x["date"], value: Number(x["value"]) })), v = view(d); return { ...value(rows, d["code"], providerId), name: v.name, unit: v.unit, direction: v.direction, denominatorLabel: d["denominator_metric"] ? metricOf(d["denominator_metric"])?.label : undefined, trend: t, ...(t.length > 1 ? { previous: t.at(-2)!.value } : {}) }; });
}
export async function list(c: Ctx) { const rows = await snapshot(c.pid); return (await definitions(c.pid)).map((d) => ({ ...view(d), current: value(rows, d["code"], c.access.providerId) })); }
const providers = (c: Ctx) => query(pool, `SELECT id, code, name FROM providers WHERE project_id=? ${c.access.providerId ? "AND id=?" : ""} ORDER BY code`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid]);
export async function get(c: Ctx, code: string) {
  const all = await query(pool, "SELECT d.*, u.name AS approver FROM indicator_definitions d LEFT JOIN users u ON u.id=d.approved_by WHERE d.project_id=? AND d.code=? ORDER BY d.version_no DESC", [c.pid, code]), d = all.find((x) => x["status"] === "active") ?? all[0] ?? notFound("Indicator"), rows = await snapshot(c.pid), total = value(rows, code, c.access.providerId), card = (await cards(c.pid, c.access.providerId, [code]))[0];
  const COL: Record<string, string> = { trainee_attendance_rate: "SUM(s.att_present_to_date)/NULLIF(SUM(s.att_sessions_to_date),0)", eligible_enrolled_trainee_rate: "AVG(s.eligibility_status='eligible')", trainee_dropout_rate: "AVG(s.dropout_status='yes' OR s.system_dropout_final)", training_completion_rate: "AVG(s.completion_status='yes')", training_certification_rate: "AVG(s.certification_status='yes')" };
  const dis = async (dimension: string, col: string, join: string) => ({ dimension, items: COL[code] ? (await query(pool, `SELECT ${col} AS label, ${COL[code]} AS v FROM trainee_status s ${join} WHERE s.project_id=? AND s.roster_status IN ('active','reserve') ${c.access.providerId ? "AND s.provider_id=?" : ""} GROUP BY ${col} ORDER BY ${col}`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid])).map((r) => ({ label: String(r["label"] ?? "Unknown"), value: r["v"] === null ? undefined : Math.round(Number(r["v"]) * 1000) / 10 })) : [] });
  return { indicator: { ...view(d), operationalDefinition: d["operational_definition"] ?? "", dataSources: d["data_sources"] ?? "", frequency: d["frequency"] ?? "", computation: d["computation_text"] ?? "", disaggregations: json<string[]>(d["disaggregations_json"], []), paymentLinkage: d["payment_linkage"] ?? undefined, version: d["version_no"], effectiveFrom: d["effective_from"] ?? String(d["created_at"]).slice(0, 10), comparator: d["comparator"], numeratorMetric: d["numerator_metric"], denominatorMetric: d["denominator_metric"] ?? undefined, numeratorLabel: metricOf(d["numerator_metric"])?.label ?? d["numerator_metric"], denominatorLabel: d["denominator_metric"] ? metricOf(d["denominator_metric"])?.label ?? d["denominator_metric"] : undefined }, rows: (await providers(c)).map((p) => ({ providerId: p["id"], providerCode: p["code"], providerName: p["name"], ...value(rows, code, String(p["id"])) })), total, trend: card?.trend ?? [], versions: all.map((v) => ({ version: v["version_no"], status: v["status"], effectiveFrom: v["effective_from"] ?? String(v["created_at"]).slice(0, 10), changeNote: v["change_note"] ?? "", approvedBy: v["approver"] ?? undefined })), disaggregation: [await dis("Sex", "s.sex", ""), await dis("Location", "l.name", "LEFT JOIN locations l ON l.id=s.location_id")] };
}
const TEXT: Record<string, string> = { name: "name", operationalDefinition: "operational_definition", dataSources: "data_sources", frequency: "frequency", computation: "computation_text", paymentLinkage: "payment_linkage", defaultTarget: "default_target", numeratorMetric: "numerator_metric", denominatorMetric: "denominator_metric", comparator: "comparator", direction: "direction", verificationMethod: "verification_method", effectiveFrom: "effective_from", changeNote: "change_note" };
/** An indicator is saved only when it can be calculated. */
async function checkFormula(c: Ctx, numerator: string, denominator: string | null, unit: string): Promise<void> {
  const known = new Set((await metrics(c)).map((m) => m.key));
  if (!known.has(numerator)) invalid("numeratorMetric", "Choose a variable from the list.");
  if (denominator && !known.has(denominator)) invalid("denominatorMetric", "Choose a variable from the list.");
  if (unit === "percent" && !denominator) invalid("denominatorMetric", "A percentage needs a denominator.");
  if (unit === "count" && denominator) invalid("denominatorMetric", "A number has no denominator.");
}
export async function propose(c: Ctx, code: string, b: Row) {
  const d = (await one(pool, "SELECT * FROM indicator_definitions WHERE project_id=? AND code=? AND status='active'", [c.pid, code])) ?? notFound("Indicator"), v = Number((await one(pool, "SELECT MAX(version_no) AS v FROM indicator_definitions WHERE project_id=? AND code=?", [c.pid, code]))!["v"]) + 1;
  if (b["numeratorMetric"] !== undefined || b["denominatorMetric"] !== undefined) await checkFormula(c, b["numeratorMetric"] ?? d["numerator_metric"], b["denominatorMetric"] === undefined ? d["denominator_metric"] : b["denominatorMetric"], d["unit"]);
  await transaction(async (tx) => {
    const { id: _i, created_at: _c, updated_at: _u, approved_by: _a, approved_at: _t, ...copy } = d;
    const id = await insert(tx, "indicator_definitions", { ...copy, ...Object.fromEntries(Object.entries(TEXT).filter(([k]) => b[k] !== undefined).map(([k, col]) => [col, b[k]])), version_no: v, status: "draft" });
    await audit(tx, c, { module: "indicators", action: "version_proposed", entityType: "indicator", entityId: id, summary: `${d["name"]}: version ${v} proposed`, after: b });
  });
  return { version: v };
}
export async function approve(c: Ctx, code: string, version: number) {
  await transaction(async (tx) => {
    const d = (await one(tx, "SELECT * FROM indicator_definitions WHERE project_id=? AND code=? AND version_no=? FOR UPDATE", [c.pid, code, version])) ?? notFound("Version");
    if (d["status"] !== "draft") conflict("NOT_DRAFT", "Only a proposed version can be approved.");
    await execute(tx, "UPDATE indicator_definitions SET status='retired' WHERE project_id=? AND code=? AND status='active'", [c.pid, code]);
    await execute(tx, "UPDATE indicator_definitions SET status='active', approved_by=?, approved_at=UTC_TIMESTAMP(3) WHERE id=?", [c.user.id, d["id"]]);
    await queueKpis(tx, c.pid);
    await audit(tx, c, { module: "indicators", action: "version_approved", entityType: "indicator", entityId: String(d["id"]), summary: `${d["name"]}: version ${version} approved` });
  });
  return get(c, code);
}
export async function create(c: Ctx, b: Row) {
  if (await one(pool, "SELECT 1 AS x FROM indicator_definitions WHERE project_id=? AND code=?", [c.pid, b["code"]])) invalid("code", "Another indicator uses this code.");
  await checkFormula(c, b["numeratorMetric"], b["denominatorMetric"] ?? null, b["unit"] === "#" ? "count" : "percent");
  const id = await insert(pool, "indicator_definitions", { project_id: c.pid, code: b["code"], version_no: 1, status: "active", protocol_no: b["no"], name: b["name"], unit: b["unit"] === "#" ? "count" : "percent", level: b["level"], purpose: "monitoring", operational_definition: b["operationalDefinition"], numerator_metric: b["numeratorMetric"], denominator_metric: b["denominatorMetric"] ?? null, direction: b["direction"], default_target: b["defaultTarget"], comparator: b["direction"] === "lower_is_better" ? "<=" : ">=", verification_method: "none", display_order: 99 });
  await audit(pool, c, { module: "indicators", action: "created", entityType: "indicator", entityId: id, summary: `Indicator ${b["name"]} created`, after: b });
  await queueKpis(pool, c.pid);
  return get(c, b["code"]);
}
export async function retire(c: Ctx, code: string) { const d = (await one(pool, "SELECT id, name FROM indicator_definitions WHERE project_id=? AND code=? AND status='active'", [c.pid, code])) ?? notFound("Indicator"); await transaction(async (tx) => { await execute(tx, "UPDATE indicator_definitions SET status='retired' WHERE id=?", [d["id"]]); await audit(tx, c, { module: "indicators", action: "retired", entityType: "indicator", entityId: d["id"], summary: `Indicator ${d["name"]} retired` }); }); }
/** Every variable an indicator can use, with today's project total, so its effect is visible before it is used. */
export async function metrics(c: Ctx) {
  const inputs = await loadInputs(pool, c.pid), acts = await query(pool, "SELECT code, name FROM activity_definitions WHERE project_id=? AND is_active=1 ORDER BY sort_order, id", [c.pid]);
  const keys: [string, string, string][] = [...Object.entries(METRICS).map(([k, m]): [string, string, string] => [k, m.label, m.help]), ...acts.map((a): [string, string, string] => [`provider.activity_approved:${a["code"]}`, `Activity approved: ${a["name"]}`, "Providers whose evidence for this activity is approved."])];
  return keys.map(([key, label, help]) => ({ key, label, help, total: inputs.reduce((n, p) => n + metricOf(key)!.of(p), 0) }));
}
export const listStages = (c: Ctx, code: string) => query(pool, "SELECT id, stage_key AS stageKey, label, offset_days AS offsetDays, is_final AS isFinal, sort_order AS sortOrder, is_active AS active FROM indicator_stages WHERE project_id=? AND indicator_code=? ORDER BY sort_order", [c.pid, code]);
export async function saveStage(c: Ctx, code: string, b: Row) {
  await transaction(async (tx) => { await execute(tx, "INSERT INTO indicator_stages (project_id, indicator_code, stage_key, label, offset_days, is_final, sort_order, is_active) VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE label=VALUES(label), offset_days=VALUES(offset_days), is_final=VALUES(is_final), sort_order=VALUES(sort_order), is_active=VALUES(is_active)", [c.pid, code, b["stageKey"], b["label"], b["offsetDays"], b["isFinal"], b["sortOrder"], b["active"]]); await audit(tx, c, { module: "indicators", action: "stage_saved", entityType: "indicator", entityId: code, summary: `Stage ${b["stageKey"]} of ${code} saved`, after: b }); });
  return listStages(c, code);
}
export async function targets(c: Ctx) {
  const defs = (await definitions(c.pid)).map(view), ps = await providers(c), now = await resolveTargets(pool, c.pid, today()), cells: Record<string, Record<string, number | undefined>> = {};
  for (const d of defs) { cells[d.code] = {}; const base = now.filter((t) => t["code"] === d.code && t["providerId"] === null).at(-1); cells[d.code]!["project"] = num(base?.["value"]); for (const p of ps) cells[d.code]![p["id"]] = num(now.filter((t) => t["code"] === d.code && t["providerId"] === p["id"]).at(-1)?.["value"]); }
  const h = await query(pool, `SELECT t.*, u.name AS byName FROM indicator_targets t LEFT JOIN users u ON u.id=t.set_by WHERE t.project_id=? ${c.access.providerId ? "AND (t.provider_id IS NULL OR t.provider_id=?)" : ""} ORDER BY t.id DESC LIMIT 300`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid]);
  return { indicators: defs, providers: ps, cells, history: h.map((t) => ({ indicatorCode: t["indicator_code"], providerId: t["provider_id"] ?? undefined, value: Number(t["target_value"]), effectiveFrom: t["effective_from"], effectiveTo: t["effective_to"] ?? undefined, note: t["note"] ?? undefined, setBy: t["byName"] ?? "" })) };
}
export async function setTarget(c: Ctx, b: { indicatorCode: string; providerId: string | null; value: number; effectiveFrom: string; note: string }) {
  const d = (await one(pool, "SELECT * FROM indicator_definitions WHERE project_id=? AND code=? AND status='active'", [c.pid, b.indicatorCode])) ?? invalid("indicatorCode", "Choose an indicator.");
  if (b.providerId && !(await one(pool, "SELECT 1 AS x FROM providers WHERE id=? AND project_id=?", [b.providerId, c.pid]))) invalid("providerId", "Choose a provider.");
  if (d["unit"] === "percent" && b.value > 100) invalid("value", "A percentage cannot be above 100.");
  await transaction(async (tx) => {
    await execute(tx, "UPDATE indicator_targets SET effective_to=DATE_SUB(?, INTERVAL 1 DAY) WHERE project_id=? AND indicator_code=? AND provider_id<=>? AND effective_to IS NULL AND effective_from<?", [b.effectiveFrom, c.pid, b.indicatorCode, b.providerId, b.effectiveFrom]);
    await execute(tx, "INSERT INTO indicator_targets (project_id, indicator_code, provider_id, target_value, comparator, effective_from, note, set_by) VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE target_value=VALUES(target_value), note=VALUES(note), set_by=VALUES(set_by)", [c.pid, b.indicatorCode, b.providerId, b.value, d["comparator"], b.effectiveFrom, b.note, c.user.id]);
    await queueKpis(tx, c.pid);
    await audit(tx, c, { module: "indicators", action: "target_set", entityType: "target", entityId: b.indicatorCode, providerId: b.providerId, summary: `Target of ${d["name"]}: ${b.value}`, after: b });
  });
  return { ok: true };
}
export async function report(c: Ctx) {
  const asOf = c.query["asOf"], rows = await snapshot(c.pid, asOf), defs = (await definitions(c.pid)).map(view), ps = await providers(c);
  return { asOf: rows[0]?.["as_of_date"] ?? today(), indicators: defs, rows: ps.map((p) => ({ provider: p, cells: defs.map((d) => value(rows, d.code, String(p["id"]))) })), totals: defs.map((d) => value(rows, d.code, c.access.providerId)) };
}
export const trend = (c: Ctx) => query(pool, "SELECT as_of_date AS date, value FROM kpi_snapshots WHERE project_id=? AND layer='monitoring' AND indicator_code=? AND provider_key=? ORDER BY as_of_date", [c.pid, c.query["indicator"] ?? "", c.access.providerId ?? c.query["providerId"] ?? "0"]);
export const recompute = async (c: Ctx) => ({ jobId: await enqueue(pool, "kpi.recompute", {}, { projectId: c.pid, userId: c.user.id }) });
export async function status(c: Ctx) { const r = await one(pool, "SELECT MAX(computed_at) AS at FROM kpi_snapshots WHERE project_id=?", [c.pid]), p = await one(pool, "SELECT COUNT(*) AS n FROM jobs WHERE project_id=? AND type='kpi.recompute' AND status IN ('queued','running')", [c.pid]); return { lastComputed: r?.["at"] ?? null, pending: p!["n"] }; }
