import { one, pool, query, type Row } from "../../core/db/db.js";
import { cards } from "../indicators/index.js";

/** What anyone may see without signing in: totals of the whole programme only. Nothing per provider, per training or per person. */
const PROJECT = "1";
/** A group smaller than this is joined with "Other", so nobody can be recognised from a chart. */
const SMALL = 10;
const num = (x: unknown) => Number(x ?? 0);
const TRACKED = "t.project_id=? AND t.roster_status IN ('active','reserve')";
const FIELDS: [RegExp, string][] = [[/cyber/i, "Cybersecurity"], [/market/i, "Digital marketing"], [/cloud|network|infrastructure/i, "Cloud, network and IT infrastructure"], [/software|stack|web|enterprise/i, "Software and web development"], [/graphic|multimedia/i, "Graphics and multimedia design"], [/maintenance|support/i, "Device maintenance and system support"]];
export const field = (title: string) => FIELDS.find(([re]) => re.test(title))?.[1] ?? "Advanced digital skills";
interface Slice { label: string; value: number }
/** Joins small groups. One small group alone could be worked out from the total, so it takes the next smallest with it. */
export function safe(rows: Slice[]): Slice[] {
  const other = rows.filter((r) => r.label === "Other" || r.value < SMALL), keep = rows.filter((r) => !other.includes(r)).sort((a, b) => b.value - a.value);
  if (other.length === 1 && other[0]!.label !== "Other" && keep.length) other.push(keep.pop()!);
  const n = other.reduce((a, r) => a + r.value, 0);
  while (n > 0 && other.reduce((a, r) => a + r.value, 0) < SMALL && keep.length) other.push(keep.pop()!);
  const total = other.reduce((a, r) => a + r.value, 0);
  return total ? [...keep, { label: "Other", value: total }] : keep;
}
async function build() {
  const q = (sql: string) => query(pool, sql, [PROJECT]), by = async (expr: string, join = "", where = "") => (await q(`SELECT ${expr} AS label, COUNT(*) AS value FROM trainees t ${join} WHERE ${TRACKED} ${where} GROUP BY 1 ORDER BY 2 DESC`)).map((r): Slice => ({ label: String(r["label"] ?? "Other"), value: num(r["value"]) }));
  const p = (await one(pool, "SELECT title, donor, sector FROM projects WHERE id=?", [PROJECT])) ?? {};
  const t = (await one(pool, `SELECT COUNT(*) AS n, SUM(t.sex='female') AS f, SUM(t.sex='male') AS m, SUM(t.is_pwd=1) AS pwd, SUM(t.is_idp=1) AS idp, SUM(t.is_returnee=1) AS ret, SUM(t.is_low_income=1) AS low FROM trainees t WHERE ${TRACKED}`, [PROJECT]))!;
  const s = (await one(pool, "SELECT SUM(dropout_status<>'yes' AND NOT system_dropout_final) AS stay, SUM(completion_status='yes') AS c, SUM(certification_status='yes') AS ce, SUM(placement_status='yes') AS j, SUM(retention_3m_status='yes') AS r FROM trainee_status WHERE project_id=? AND roster_status IN ('active','reserve')", [PROJECT]))!;
  const reported = new Set((await q("SELECT DISTINCT report_type AS t FROM outcome_reports WHERE project_id=? AND status='accepted'")).map((r) => r["t"] as string));
  const c = (await one(pool, "SELECT COUNT(*) AS n, SUM(effective_end<CURRENT_DATE) AS ended, SUM(COALESCE(actual_start,planned_start)<=CURRENT_DATE AND effective_end>=CURRENT_DATE) AS running, MIN(COALESCE(actual_start,planned_start)) AS a, MAX(effective_end) AS b FROM training_classes WHERE project_id=? AND is_cancelled=0", [PROJECT]))!;
  const x = (await one(pool, `SELECT (SELECT COUNT(*) FROM providers WHERE project_id=? AND status='active') AS providers, (SELECT COUNT(*) FROM trainings WHERE project_id=?) AS trainings, (SELECT COUNT(*) FROM training_sites WHERE project_id=?) AS sites, (SELECT COUNT(*) FROM attendance_sessions a JOIN training_classes k ON k.id=a.class_id WHERE k.project_id=?) AS sessions,
    (SELECT COUNT(*) FROM outcome_reports WHERE project_id=? AND status='accepted') AS reports, (SELECT COALESCE(SUM(a.marks_count),0) FROM attendance_sessions a JOIN training_classes k ON k.id=a.class_id WHERE k.project_id=?) AS marks`, Array(6).fill(PROJECT)))!;
  const months = await q(`SELECT DATE_FORMAT(t.created_at,'%Y-%m') AS m, COUNT(*) AS n FROM trainees t WHERE ${TRACKED} GROUP BY 1 ORDER BY 1`);
  const weeks = await q("SELECT DATE_SUB(a.session_date, INTERVAL WEEKDAY(a.session_date) DAY) AS w, SUM(a.present_count+a.excused_count) AS p, SUM(a.marks_count) AS n FROM attendance_sessions a JOIN training_classes k ON k.id=a.class_id WHERE k.project_id=? GROUP BY 1 HAVING n>=200 ORDER BY 1");
  const trainings = await q(`SELECT tr.title, COUNT(*) AS n FROM trainees t JOIN trainings tr ON tr.id=t.training_id WHERE ${TRACKED} GROUP BY tr.id, tr.title`), fields = new Map<string, number>();
  for (const r of trainings) fields.set(field(r["title"]), (fields.get(field(r["title"])) ?? 0) + num(r["n"]));
  const g = await q("SELECT category AS label, COUNT(*) AS value, SUM(status IN ('resolved','closed')) AS resolved FROM grievance_cases WHERE project_id=? GROUP BY 1 ORDER BY 2 DESC");
  const kpis = (await cards(PROJECT, null)).filter((k) => k.unit === "%" && k.indicatorCode !== "timely_grievance_resolution_rate");
  const defs = await q("SELECT code, name, protocol_no AS no, level, unit FROM indicator_definitions WHERE project_id=? AND status='active' AND protocol_no BETWEEN 1 AND 18 ORDER BY protocol_no");
  let total = 0;
  return {
    asOf: new Date().toISOString(), project: { title: p["title"], donor: p["donor"], sector: p["sector"] },
    providers: num(x["providers"]), trainings: num(x["trainings"]), trainees: num(t["n"]), femalePct: t["n"] ? Math.round((num(t["f"]) / num(t["n"])) * 100) : 0,
    female: num(t["f"]), male: num(t["m"]), classes: { total: num(c["n"]), ended: num(c["ended"]), running: num(c["running"]), from: c["a"], to: c["b"] }, sites: num(x["sites"]), sessions: num(x["sessions"]), marks: num(x["marks"]), reports: num(x["reports"]),
    journey: ([["Enrolled", num(t["n"]), true], ["In training or not dropped out", num(s["stay"]), true], ["Completed", num(s["c"]), reported.has("completion")], ["Certified", num(s["ce"]), reported.has("certification")], ["In employment", num(s["j"]), reported.has("employment_placement")], ["Still employed after 3 months", num(s["r"]), reported.has("job_retention_3m")]] as const).map(([label, value, known]) => ({ label, ...(known ? { value } : {}) })),
    enrolment: months.map((m) => ({ month: m["m"] as string, value: num(m["n"]), total: (total += num(m["n"])) })),
    attendance: weeks.map((w) => ({ week: w["w"] as string, value: Math.round((num(w["p"]) / num(w["n"])) * 1000) / 10 })),
    age: safe(await by("CASE WHEN t.age_years BETWEEN 18 AND 20 THEN '18–20' WHEN t.age_years BETWEEN 21 AND 23 THEN '21–23' WHEN t.age_years BETWEEN 24 AND 26 THEN '24–26' WHEN t.age_years BETWEEN 27 AND 29 THEN '27–29' ELSE 'Other' END")).sort((a, b) => (a.label < b.label ? -1 : 1)),
    education: safe(await by("CASE t.education_code WHEN 'bachelor' THEN 'Bachelor’s degree' WHEN 'above_bachelor' THEN 'Above bachelor’s degree' WHEN 'diploma' THEN 'Diploma' WHEN 'tvet_1_4' THEN 'TVET levels I–IV' WHEN 'secondary' THEN 'Secondary (grades 9–12)' WHEN 'high_school_dropout' THEN 'High school, not completed' ELSE 'Other' END")),
    employment: safe(await by("CASE t.employment_code WHEN 'not_working' THEN 'Not working' WHEN 'underemployed' THEN 'Underemployed' ELSE 'Occasional work or not stated' END")),
    regions: safe(await by("COALESCE(r.name,'Other')", "LEFT JOIN regions r ON r.code=t.region_code")),
    locations: safe(await by("COALESCE(l.name,'Other')", "JOIN training_sites st ON st.id=t.site_id LEFT JOIN locations l ON l.id=st.location_id")),
    levels: safe(await by("CONCAT(UPPER(LEFT(tr.level,1)), SUBSTRING(tr.level,2))", "JOIN trainings tr ON tr.id=t.training_id")),
    fields: safe([...fields].map(([label, value]) => ({ label, value }))),
    inclusion: ([["Women", t["f"]], ["From low-income households", t["low"]], ["Persons with disabilities", t["pwd"]], ["Internally displaced persons", t["idp"]], ["Returnees", t["ret"]]] as const).map(([label, v]) => ({ label, value: num(v) })).filter((r) => r.value >= SMALL),
    feedback: { total: g.reduce((a, r) => a + num(r["value"]), 0), resolved: g.reduce((a, r) => a + num(r["resolved"]), 0), byCategory: safe(g.map((r) => ({ label: String(r["label"]), value: num(r["value"]) }))) },
    results: kpis.map((k) => ({ code: k.indicatorCode, name: k.name, value: k.value, target: k.target, numerator: k.numerator, denominator: k.denominator, denominatorLabel: k.denominatorLabel, lowerBetter: k.direction === "lower_is_better", verified: k.verified })),
    indicators: defs.map((d: Row) => ({ no: d["no"], name: d["name"], level: d["level"] })),
  };
}
let kept: { at: number; value: ReturnType<typeof build> } | null = null;
/** Kept for ten minutes: however many visitors come, the database is asked once. */
export function publicStats() {
  if (kept && Date.now() - kept.at < 600_000) return kept.value;
  const value = build();
  kept = { at: Date.now(), value };
  value.catch(() => { kept = null; });
  return value;
}
