import { json, one, pool, query, type Row } from "../../core/db/db.js";
import { audit } from "../../core/audit/audit.js";
import { loadFile, storeFile } from "../../core/files/files.js";
import { toCsv, toXlsx } from "../../core/files/table.js";
import { can, deny, invalid, like, notFound, sameProvider, scope, type Ctx } from "../../core/http/route.js";
import { defineJob, enqueue, getJob } from "../../core/jobs/jobs.js";
import { addDays, diffDays, today } from "../../shared/dates.js";
import { cached } from "../../core/cache.js";
import { accessFor } from "../access/index.js";
import { compliance } from "../activities/index.js";
import { allClasses, rate } from "../delivery/index.js";
import { cards, snapshot, value } from "../indicators/index.js";
import { board } from "../outcomes/index.js";
import { providerView } from "../providers/index.js";
import { traineeRows } from "../registration/index.js";
import { runs } from "../verification/index.js";
import { CATALOGUE, type Params } from "./catalogue.service.js";
import { toDocx, toPdf } from "./documents.js";

export const catalogue = (c: Ctx) => CATALOGUE.filter((e) => !e.perm || can(c, e.perm)).map(({ key, title, description, formats, params }) => ({ key, title, description, formats, params }));
export async function generate(c: Ctx, key: string, b: Params & { format: string }) {
  const e = CATALOGUE.find((x) => x.key === key) ?? notFound("Report");
  if (e.perm && !can(c, e.perm)) deny();
  if (!e.formats.includes(b.format as never)) invalid("format", `Choose ${e.formats.join(", ")}.`);
  if (b.providerId) sameProvider(c, b.providerId);
  await audit(pool, c, { module: "reporting", action: "report_requested", entityType: "report", entityId: key, providerId: b.providerId ?? null, summary: `${e.title} (${b.format})`, after: b });
  return { jobId: await enqueue(pool, "reports.generate", { key, ...b }, { projectId: c.pid, userId: c.user.id }) };
}
/** The job runs with the requester's own access, loaded again at that moment. */
defineJob("reports.generate", async (job) => {
  const access = await accessFor(job.userId!, job.projectId!), e = CATALOGUE.find((x) => x.key === job.payload["key"])!, b = job.payload as Params & { format: string };
  if (!access || (e.perm && !access.permissions.has(e.perm))) deny();
  const c = { pid: job.projectId!, access, user: { id: job.userId! }, query: {}, params: {}, ip: "", req: { id: `job_${job.id}` } } as unknown as Ctx, r = await e.build(c, b);
  await job.progress(60, "Writing the file");
  const first = r.sections.filter((s) => s.header), data = b.format === "pdf" ? await toPdf(r) : b.format === "docx" ? await toDocx(r) : b.format === "xlsx" ? await toXlsx(r.title, first[0]?.header ?? [], first[0]?.rows ?? []) : Buffer.from(toCsv(first[0]?.header ?? [], first[0]?.rows ?? []));
  const id = await storeFile(pool, { projectId: c.pid, purpose: "report", name: `${e.key}_${today()}.${b.format}`, data, userId: job.userId, trusted: true });
  return { message: "Your report is ready.", href: `/projects/${c.pid}/files/${id}` };
});
/** Generated files belong to the person who asked for them. */
export async function file(c: Ctx, fid: string) { if (!(await one(pool, "SELECT 1 AS x FROM files WHERE id=? AND project_id=? AND purpose IN ('report','export') AND uploaded_by=?", [fid, c.pid, c.user.id]))) notFound("File"); return loadFile(fid); }
export async function job(c: Ctx, jid: string) {
  const j = await getJob(c.pid, jid);
  if (!j || (j["requested_by"] !== null && j["requested_by"] !== c.user.id)) notFound("Job");
  return { id: j!["id"], status: j!["status"] === "dead" ? "failed" : j!["status"], progressPct: j!["progress_pct"] ?? 0, progressNote: j!["progress_note"] ?? "", result: json(j!["result_json"], undefined), error: j!["status"] === "failed" ? (j!["last_error"] ?? "The task failed.") : undefined };
}
const KINDS: Record<string, { perm: string; type: string }> = { "datahealth": { perm: "datahealth.view", type: "datahealth.run" }, "recompute": { perm: "kpi.recompute", type: "kpi.recompute" }, "kpi": { perm: "kpi.recompute", type: "kpi.recompute" }, "duplicates": { perm: "duplicate.review", type: "duplicates.scan" }, "reminders": { perm: "notification.manage", type: "reminders.run" }, "attendance": { perm: "project.manage", type: "attendance.recomputeAll" } };
export async function startJob(c: Ctx, kind: string, params: Row) {
  if (/export|trainee/.test(kind)) return generate(c, "trainees", { format: "xlsx", ...params });
  const k = KINDS[kind.split(/[._-]/)[0]!] ?? notFound("Task");
  if (!can(c, k.perm)) deny();
  return { jobId: await enqueue(pool, k.type, {}, { projectId: c.pid, userId: c.user.id }) };
}
const MATRIX = ["registered_enrolled_trainees_count", "trainee_attendance_rate", "trainee_dropout_rate", "training_completion_rate", "training_certification_rate", "employment_placement_rate", "timely_grievance_resolution_rate"];
const HEAD = [...MATRIX, "eligible_enrolled_trainee_rate"];
/** Reads stored values only; nothing is recalculated on page load. */
export const programme = (c: Ctx) => cached(c, "programme", () => buildProgramme(c));
async function buildProgramme(c: Ctx) {
  const raw = (c.req.query as Row)["providerId"], wanted = raw ? ([] as string[]).concat(raw as string | string[]) : [], s = scope(c, { provider: "p.id" });
  const ps = (await query(pool, `SELECT p.id, p.code, p.name, p.status FROM providers p WHERE p.project_id=? AND ${s.sql} ORDER BY p.code`, [c.pid, ...s.args] as never[])).filter((p) => !wanted.length || wanted.includes(p["id"])), ids = [...ps.map((p) => p["id"] as string), "0"], snap = await snapshot(c.pid), kpis = await cards(c.pid, c.access.providerId, HEAD);
  const weeks = await query(pool, "SELECT DATE_SUB(s.session_date, INTERVAL WEEKDAY(s.session_date) DAY) AS w, s.provider_id AS p, SUM(s.present_count+s.excused_count) AS n, SUM(s.marks_count) AS d FROM attendance_sessions s WHERE s.provider_id IN (?) AND s.session_date>=? GROUP BY w, p ORDER BY w", [ids, addDays(today(), -84)]), trend = [...new Set(weeks.map((w) => w["w"] as string))].map((w) => { const m = weeks.filter((x) => x["w"] === w), row: Record<string, number | string> = { week: w }; for (const p of ps) { const x = m.find((y) => y["p"] === p["id"] || String(y["p"]) === p["id"]), v = x ? rate(x["n"], x["d"]) : undefined; if (v !== undefined) row[p["code"]] = v; } const t = rate(m.reduce((a, x) => a + x["n"], 0), m.reduce((a, x) => a + x["d"], 0)); if (t !== undefined) row["Project"] = t; return row; });
  const f = (await one(pool, "SELECT COUNT(*) AS r, SUM(dropout_status<>'yes' AND NOT system_dropout_final) AS a, SUM(completion_status='yes') AS c, SUM(certification_status='yes') AS t, SUM(placement_status='yes') AS j FROM trainee_status WHERE provider_id IN (?) AND roster_status IN ('active','reserve')", [ids]))!, ob = await query(pool, "SELECT p.code, SUM(o.status='approved') AS approved, SUM(o.status='submitted') AS submitted, SUM(o.status IN ('open','returned')) AS open, SUM(o.status='overdue') AS overdue FROM providers p LEFT JOIN activity_obligations o ON o.provider_id=p.id WHERE p.id IN (?) GROUP BY p.code ORDER BY p.code", [ids]);
  const g = (await one(pool, "SELECT COUNT(*) AS o, SUM(submitted_at>=UTC_TIMESTAMP(3)-INTERVAL 3 DAY) AS a, SUM(submitted_at<UTC_TIMESTAMP(3)-INTERVAL 10 DAY) AS z FROM grievance_cases WHERE provider_id IN (?) AND first_response_at IS NULL AND status NOT IN ('resolved','closed')", [ids]))!, dh = await query(pool, "SELECT provider_id AS p, check_key AS k, SUM(severity='error') AS e, SUM(severity='warning') AS w FROM datahealth_findings WHERE provider_id IN (?) AND resolved_at IS NULL GROUP BY p, k", [ids]), N = (v: unknown) => Number(v ?? 0);
  const defs = new Map(kpis.map((k) => [k.indicatorCode, k])), pending = await one(pool, "SELECT COUNT(*) AS n FROM jobs WHERE project_id=? AND type='kpi.recompute' AND status IN ('queued','running')", [c.pid]);
  return { asOf: snap[0]?.["computed_at"] ?? new Date().toISOString(), recalculating: pending!["n"] > 0, kpis, matrixCodes: MATRIX, matrix: ps.map((p) => ({ provider: { id: p["id"], code: p["code"], name: p["name"] }, cells: MATRIX.map((code) => { const v = value(snap, code, p["id"]), d = defs.get(code); return { code, value: v.value, target: v.target, status: v.status, unit: d?.unit ?? "%", lowerBetter: d?.direction === "lower_is_better" }; }) })), trend, trendSeries: ps.map((p) => p["code"]), funnel: [["Registered", "r"], ["Active mid-course", "a"], ["Completed", "c"], ["Certified", "t"], ["Job linked", "j"], ["Employed", "e"]].map(([stage, k]) => ({ stage, value: N(f[k!]) })), obligations: ob.map((o) => ({ code: o["code"], approved: N(o["approved"]), submitted: N(o["submitted"]), open: N(o["open"]), overdue: N(o["overdue"]) })), grievances: { buckets: [{ label: "0–3 d", value: N(g["a"]) }, { label: "4–10 d", value: N(g["o"]) - N(g["a"]) - N(g["z"]) }, { label: "> 10 d", value: N(g["z"]) }], slaPct: defs.get("timely_grievance_resolution_rate")?.value ?? 0, open: N(g["o"]) }, runs: c.access.providerId || !can(c, "verification.view_subjects") ? [] : await runs(c), health: ps.map((p) => { const m = dh.filter((x) => String(x["p"]) === p["id"]); return { code: p["code"], name: p["name"], score: Math.max(0, 100 - m.reduce((a, x) => a + N(x["e"]) * 10, 0) - Math.min(40, m.reduce((a, x) => a + N(x["w"]) * 2, 0))), issues: m.slice(0, 3).map((x) => x["k"]) }; }) };
}
export async function provider(c: Ctx, pid: string) {
  sameProvider(c, pid);
  const p = await providerView(c, pid), classes = (await allClasses(c)).filter((k) => k.providerId === pid), now = today(), todo: Row[] = [], miss = classes.filter((k) => k.sessionsMissing > 0);
  if (miss.length && can(c, "attendance.view")) todo.push({ kind: "attendance", severity: "overdue", title: `${miss.length} classes have missing days (${miss.reduce((a, k) => a + k.sessionsMissing, 0)} sessions)`, href: "attendance", count: miss.length });
  for (const r of (await cached(c, "board", () => board(c), 10)).rows.filter((x) => x.cls.providerId === pid)) for (const k of r.cells.filter((x) => can(c, "outcome.view") && ["due", "overdue", "returned"].includes(x.state)).slice(0, 1)) todo.push({ kind: k.state === "returned" ? "returned" : "outcome_report", severity: k.state === "overdue" ? "overdue" : "due_soon", title: `${k.type.replace(/_/g, " ")} report of ${r.cls.code} ${k.state === "returned" ? "was returned" : "is due"}`, href: "outcomes", dueDate: k.dueDate });
  if (can(c, "activity.view")) for (const o of await query(pool, "SELECT o.id, o.status, o.due_date, d.name FROM activity_obligations o JOIN activity_definitions d ON d.id=o.definition_id WHERE o.provider_id=? AND o.status IN ('overdue','open','returned') ORDER BY o.due_date LIMIT 30", [pid])) { const left = diffDays(now, o["due_date"]); todo.push({ kind: o["status"] === "returned" ? "returned" : "obligation", severity: o["status"] === "overdue" ? "overdue" : left <= 7 ? "due_soon" : "open", title: o["status"] === "returned" ? `${o["name"]} returned for correction` : `${o["name"]} ${left < 0 ? `overdue by ${-left} days` : `due in ${left} days`}`, href: `obligations/${o["id"]}`, dueDate: o["due_date"] }); }
  const g = (await one(pool, "SELECT COUNT(*) AS n, SUM(due_at<UTC_TIMESTAMP(3)) AS o FROM grievance_cases WHERE provider_id=? AND first_response_at IS NULL AND status NOT IN ('resolved','closed')", [pid]))!;
  if (g["n"] && can(c, "grievance.view")) todo.push({ kind: "grievance", severity: Number(g["o"]) ? "overdue" : "due_soon", title: `${g["n"]} grievances need a response`, href: "grievances", count: g["n"] });
  const order: Record<string, number> = { overdue: 0, due_soon: 1, open: 2, info: 3 };
  todo.sort((a, b) => order[a["severity"]]! - order[b["severity"]]!);
  return { provider: p, todo: todo.slice(0, 60), kpis: (await cards(c.pid, pid)).map((k) => (c.access.providerId ? { ...k, verified: undefined, ...(k.indicatorCode.startsWith("tp_") ? { target: undefined, status: k.status === "no_data" ? k.status : "not_applicable" } : {}) } : k)), classes, atRisk: c.access.providerId ? null : await traineeRows(c, "t.provider_id=? AND s.system_dropout_risk=1", [pid], "ORDER BY s.att_max_reachable LIMIT 10"), checklist: [{ label: "Classes scheduled", done: classes.length > 0, href: "trainings" }, { label: "Trainees registered", done: p.registered > 0, href: "trainees" }] };
}
export async function search(c: Ctx) {
  const q = (c.query["q"] ?? "").trim();
  if (q.length < 2) return { trainees: [], providers: [], classes: [], grievances: [] };
  const w = like(q), s = scope(c, { provider: "p.id" }), gs = scope(c, { provider: "g.provider_id" });
  return { trainees: can(c, "trainee.view") ? await traineeRows(c, "(t.trainee_code LIKE ? OR t.first_name LIKE ? OR t.father_name LIKE ? OR CONCAT(t.first_name,' ',COALESCE(t.father_name,'')) LIKE ?)", [w, w, w, w], "LIMIT 8") : [], providers: can(c, "provider.view") ? await query(pool, `SELECT p.id, p.code, p.name, p.status FROM providers p WHERE p.project_id=? AND ${s.sql} AND (p.code LIKE ? OR p.name LIKE ?) LIMIT 5`, [c.pid, ...s.args, w, w] as never[]) : [], classes: can(c, "training.view") ? (await allClasses(c)).filter((k) => `${k.code} ${k.name} ${k.trainingTitle}`.toLowerCase().includes(q.toLowerCase())).slice(0, 8) : [], grievances: can(c, "grievance.view") ? await query(pool, `SELECT g.id, g.ref, g.subject, g.status FROM grievance_cases g WHERE g.project_id=? AND ${gs.sql} AND (g.ref LIKE ? OR g.subject LIKE ?) LIMIT 5`, [c.pid, ...gs.args, w, w] as never[]) : [] };
}
void compliance;
