import { one, pool, query, type Row } from "../../core/db/db.js";
import { can, notFound, scope, type Ctx } from "../../core/http/route.js";
import { coverage, coverageBy } from "../attendance/index.js";
import { compliance } from "../activities/index.js";
import { report as kpiReport } from "../indicators/index.js";
import { getTrainee } from "../registration/index.js";
import { today } from "../../shared/dates.js";
import type { Report } from "./documents.js";

export interface Params { providerId?: string | undefined; classId?: string | undefined; period?: string | undefined; traineeId?: string | undefined; runId?: string | undefined; dims?: string | undefined }
interface Entry { key: string; title: string; description: string; formats: ("pdf" | "docx" | "xlsx" | "csv")[]; params: ("provider" | "period" | "class")[]; perm?: string; build: (c: Ctx, p: Params) => Promise<Report> }
const ALL: Entry["formats"] = ["pdf", "docx", "xlsx", "csv"], n = (v: unknown) => (v === undefined || v === null ? "" : String(v));
const sub = async (c: Ctx) => `${(await one(pool, "SELECT title FROM projects WHERE id=?", [c.pid]))!["title"]} · ${today()}`;
const S = (c: Ctx, col = "t.provider_id", p: Params = {}) => { const s = scope(c, { provider: col }); return { sql: p.providerId ? `${s.sql} AND ${col}=?` : s.sql, args: [...s.args, ...(p.providerId ? [p.providerId] : [])] as string[] }; };
const table = async (c: Ctx, title: string, header: string[], rows: Row[]): Promise<Report> => ({ title, subtitle: await sub(c), sections: [{ title, header, rows: rows.map((r) => Object.values(r).map((v) => (v === null ? null : typeof v === "number" ? v : String(v)))) }] });
async function grievances(c: Ctx, p: Params) { const s = S(c, "g.provider_id", p); return query(pool, `SELECT g.*, p.code AS pc, p.name AS pn FROM grievance_cases g JOIN providers p ON p.id=g.provider_id WHERE g.project_id=? AND ${s.sql} ${p.period ? "AND DATE_FORMAT(g.submitted_at,'%Y-%m')=?" : ""} ORDER BY g.submitted_at`, [c.pid, ...s.args, ...(p.period ? [p.period] : [])]); }
const verdict = (g: Row) => (g["first_response_at"] ? (g["first_response_at"] <= g["due_at"] ? "Yes" : "No") : Date.parse(g["due_at"]) < Date.now() ? "No" : "Pending");
export const CATALOGUE: Entry[] = [
  { key: "indicators_summary", title: "Indicator summary", description: "All indicators by provider with targets and verified values.", formats: ALL, params: [], perm: "indicator.view", build: async (c) => { const r = await kpiReport(c), head = ["Indicator", ...r.rows.map((x) => String(x.provider["code"])), "All", "Target"]; return { title: "Indicator summary", subtitle: `${await sub(c)} · values of ${r.asOf}`, sections: [{ title: "Monitoring values", header: head, rows: r.indicators.map((d, i) => [d.name, ...r.rows.map((x) => n(x.cells[i]!.value)), n(r.totals[i]!.value), n(r.totals[i]!.target)]) }] }; } },
  { key: "claimed_verified", title: "Claimed and verified", description: "What providers reported next to what verification confirmed.", formats: ALL, params: [], perm: "indicator.view", build: async (c) => { const r = await kpiReport(c), rows = r.rows.flatMap((x) => r.indicators.flatMap((d, i) => { const v = x.cells[i]!; return v.value === undefined ? [] : [[String(x.provider["code"]), d.name, n(v.value), n((v as Row)["verified"]), n(v.target), v.status as string]]; })); return { title: "Claimed and verified", subtitle: await sub(c), sections: [{ title: "By provider and indicator", header: ["Provider", "Indicator", "Claimed", "Verified", "Target", "Status"], rows }] }; } },
  { key: "activities_compliance", title: "Activity compliance", description: "Approved and required activities by provider.", formats: ALL, params: [], perm: "activity.view", build: async (c) => { const r = await compliance(c); return { title: "Activity compliance", subtitle: await sub(c), sections: [{ title: "Approved / required", header: ["Provider", ...r.activities.map((a) => String(a.name))], rows: r.rows.map((x) => [String(x.providerCode), ...x.cells.map((k) => (k.total ? `${k.approved}/${k.total} ${k.status}` : "–"))]) }] }; } },
  { key: "feedback_summary", title: "Feedback summary", description: "Cases, responses and timeliness by provider.", formats: ALL, params: ["provider", "period"], perm: "grievance.view", build: async (c, p) => { const g = await grievances(c, p), codes = [...new Set(g.map((x) => x["pc"] as string))]; return { title: "Feedback summary", subtitle: await sub(c), sections: [{ title: "By provider", header: ["Provider", "Total", "Responded", "Timely", "Late", "No response", "Pending", "Timely rate"], rows: codes.map((k) => { const m = g.filter((x) => x["pc"] === k), y = m.filter((x) => verdict(x) === "Yes").length, r = m.filter((x) => x["first_response_at"]).length, no = m.filter((x) => !x["first_response_at"] && verdict(x) === "No").length, d = r + no; return [k, m.length, r, y, r - y, no, m.length - d, d ? `${Math.round((y / d) * 1000) / 10} %` : "–"]; }) }] }; } },
  { key: "feedback_detailed", title: "Feedback details", description: "Every case with its dates and timeliness.", formats: ALL, params: ["provider", "period"], perm: "grievance.view", build: async (c, p) => ({ title: "Feedback details", subtitle: await sub(c), sections: [{ title: "Cases", header: ["Reference", "Provider", "Category", "Subject", "Submitted", "Due", "First response", "Status", "Timely"], rows: (await grievances(c, p)).map((g) => [g["ref"], g["pc"], g["category"], g["subject"], n(g["submitted_at"]).slice(0, 10), n(g["due_at"]).slice(0, 10), n(g["first_response_at"]).slice(0, 10), g["status"], verdict(g)]) }] }) },
  { key: "provider_profile", title: "Provider profile", description: "Contract, trainees, classes and indicators of one provider.", formats: ["pdf", "docx"], params: ["provider"], build: async (c, p) => { const id = c.access.providerId ?? p.providerId, v = (await one(pool, "SELECT * FROM providers WHERE id=? AND project_id=?", [id ?? "0", c.pid])) ?? notFound("Provider"), k = await one(pool, "SELECT * FROM provider_contracts WHERE provider_id=? AND status='active' LIMIT 1", [id!]), t = (await one(pool, "SELECT SUM(roster_status='active') AS a, SUM(roster_status='reserve') AS r, SUM(sex='female') AS f, SUM(sex='male') AS m FROM trainees WHERE provider_id=? AND roster_status IN ('active','reserve')", [id!]))!, cls = await query(pool, "SELECT c.code, t.title, l.name AS loc, COALESCE(c.actual_start,c.planned_start) AS s, c.effective_end AS e, k.tracked_trainees AS n, k.sessions_missing AS m FROM training_classes c JOIN trainings t ON t.id=c.training_id JOIN training_sites x ON x.id=c.site_id LEFT JOIN locations l ON l.id=x.location_id LEFT JOIN class_counters k ON k.class_id=c.id WHERE c.provider_id=? ORDER BY t.title, c.code", [id!]), r = await kpiReport(c), mine = r.rows.find((x) => String(x.provider["id"]) === id); return { title: v["name"], subtitle: await sub(c), sections: [{ title: "Profile", pairs: [["Code", v["code"]], ["Status", v["status"]], ["Contact", n(v["contact_name"])], ["Email", n(v["contact_email"])], ["Contract", n(k?.["contract_number"])], ["Target trainees", n(k?.["target_trainees"])], ["Active", n(t["a"])], ["Reserve", n(t["r"])], ["Female", n(t["f"])], ["Male", n(t["m"])]] }, ...(can(c, "indicator.view") ? [{ title: "Indicators", header: ["Indicator", "Value", "Target", "Status"], rows: r.indicators.map((d, i) => [d.name, n(mine?.cells[i]!.value), n(mine?.cells[i]!.target), n(mine?.cells[i]!.status)]) }] : []), { title: "Classes", header: ["Class", "Training", "Location", "Start", "End", "Trainees", "Missing days"], rows: cls.map((x) => Object.values(x).map((y) => (typeof y === "number" ? y : n(y)))) }] }; } },
  { key: "trainee_profile", title: "Trainee profile", description: "One trainee's registration, attendance and results.", formats: ["pdf", "docx"], params: [], perm: "trainee.view_pii", build: async (c, p) => { const t = (await getTrainee(c, p.traineeId ?? "0")) as Row; return { title: t["fullName"], subtitle: `${t["code"]} · ${await sub(c)}`, sections: [{ title: "Registration", pairs: [["Provider", n(t["providerName"])], ["Training", n(t["trainingTitle"])], ["Class", n(t["className"])], ["Sex", n(t["sex"])], ["Age", n(t["age"])], ["Phone", n(t["phone"])], ["Region", n(t["region"])], ["Woreda", n(t["woreda"])], ["Education", n(t["education"])], ["Employment", n(t["employment"])], ["Eligibility", n(t["eligibility"])], ["Roster", n(t["rosterStatus"])]] }, { title: "Attendance", pairs: [["Rate", `${n(t["attendanceRate"])} %`], ["Present", n(t["present"])], ["Absent", n(t["absent"])], ["Excused", n(t["excused"])]] }, { title: "Results", header: ["Result", "Status"], rows: [["Dropout", "dropout"], ["Completion", "completion"], ["Certification", "certification"], ["Employment placement", "placement"], ["Locality", "locality"], ["Retention 3 m", "retention3m"]].map(([l, k]) => [l!, n(t[k!])]) }] }; } },
  { key: "verification_summary", title: "Verification summary", description: "Results of every finished verification run.", formats: ALL, params: ["provider"], perm: "verification.view_aggregate", build: async (c, p) => { const s = S(c, "r.provider_id", p); return table(c, "Verification summary", ["Run", "Provider", "Indicator", "Period", "Sample", "Verified %", "CI low", "CI high", "Target", "Result"], await query(pool, `SELECT CAST(r.id AS CHAR) AS run, p.code, r.indicator_code, r.period_key, r.sample_size, r.verified_rate_pct, r.ci_lower_pct, r.ci_upper_pct, r.target_used, r.pathway FROM verification_runs r JOIN providers p ON p.id=r.provider_id WHERE r.project_id=? AND r.status='finalised' AND ${s.sql} ORDER BY r.id`, [c.pid, ...s.args])); } },
  { key: "verification_run", title: "Verification run", description: "One run with its strata and every result.", formats: ALL, params: [], perm: "verification.view_subjects", build: async (c, p) => { if (c.access.providerId) notFound("Run"); const r = (await one(pool, "SELECT r.*, p.name AS pn FROM verification_runs r JOIN providers p ON p.id=r.provider_id WHERE r.id=? AND r.project_id=?", [p.runId ?? "0", c.pid])) ?? notFound("Run"); return { title: `Verification run ${r["id"]}`, subtitle: await sub(c), sections: [{ title: "Run", pairs: [["Provider", r["pn"]], ["Indicator", r["indicator_code"]], ["Period", r["period_key"]], ["Tier", n(r["tier"])], ["Seed", n(r["seed"])], ["Population", n(r["population_count"])], ["Sample", n(r["sample_size"])], ["Verified %", n(r["verified_rate_pct"])], ["Interval", `${n(r["ci_lower_pct"])} to ${n(r["ci_upper_pct"])}`], ["Result", n(r["pathway"])]] }, { title: "Strata", header: ["Location", "Sex", "Population", "Primary", "Reserve"], rows: (await query(pool, "SELECT location_name, sex_key, population, primary_drawn, reserve_drawn FROM verification_strata WHERE run_id=?", [r["id"]])).map((x) => Object.values(x) as never) }, { title: "Subjects", header: ["Key", "Role", "Stratum", "Claim", "Status", "Review"], rows: (await query(pool, "SELECT subject_key, role, stratum_key, IF(tp_claim_value,'Yes','No') AS claim, status_code, supervisor_status FROM verification_subjects WHERE run_id=? ORDER BY id", [r["id"]])).map((x) => Object.values(x) as never) }] }; } },
  { key: "executive_pack", title: "Executive pack", description: "The programme in one document for management.", formats: ["pdf", "docx"], params: [], perm: "indicator.view", build: async (c) => { const parts = await Promise.all(["indicators_summary", "activities_compliance", "feedback_summary", "verification_summary"].map((k) => CATALOGUE.find((x) => x.key === k)!.build(c, {}))); return { title: "Executive pack", subtitle: await sub(c), sections: parts.flatMap((x) => x.sections.map((s) => ({ ...s, title: `${x.title}: ${s.title}` }))) }; } },
  { key: "trainees", title: "Trainee list", description: "All trainees with their status.", formats: ["xlsx", "csv"], params: ["provider", "class"], perm: "trainee.view", build: async (c, p) => { const s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" }), pii = can(c, "trainee.view_pii"), rows = await query(pool, `SELECT t.trainee_code, t.external_beneficiary_id, p.code AS prov, tr.title, k.code AS cls, t.first_name, t.father_name, t.grandfather_name, t.sex, t.age_years, ${pii ? "t.phone_e164" : "''"} AS phone, COALESCE(t.region_code,t.region_raw) AS region, t.woreda, t.education_raw, t.employment_raw, t.form_completion_date, t.roster_status, t.eligibility_status, x.att_rate_to_date, x.dropout_status, x.completion_status, x.certification_status, x.placement_status, x.locality_status, x.retention_3m_status FROM trainees t JOIN trainee_status x ON x.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN trainings tr ON tr.id=t.training_id JOIN training_classes k ON k.id=t.class_id WHERE t.project_id=? AND ${s.sql} ${p.providerId ? "AND t.provider_id=?" : ""} ${p.classId ? "AND t.class_id=?" : ""} ORDER BY t.trainee_code`, [c.pid, ...s.args, ...(p.providerId ? [p.providerId] : []), ...(p.classId ? [p.classId] : [])] as never[]); return table(c, "Trainees", ["Trainee ID", "External ID", "Provider", "Training", "Class", "First name", "Father's name", "Grandfather's name", "Sex", "Age", "Phone", "Region", "Woreda", "Education", "Employment", "Form date", "Roster", "Eligibility", "Attendance %", "Dropout", "Completion", "Certification", "Employment placement", "Locality", "Retention 3 m"], rows); } },
  { key: "attendance_rates", title: "Attendance rates per trainee", description: "Sessions attended and possible for every trainee.", formats: ["xlsx", "csv"], params: ["provider", "class"], perm: "attendance.correct.approve", build: async (c, p) => { const s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" }); return table(c, "Attendance rates", ["Provider code", "Provider", "Training", "Site", "Class", "Trainee ID", "Beneficiary ID", "Name", "Sex", "Roster", "Sessions attended", "Sessions possible", "Rate %"], await query(pool, `SELECT p.code, p.name, tr.title, st.display_name, k.code AS cls, t.trainee_code, t.external_beneficiary_id, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, t.sex, t.roster_status, s.att_present_to_date, s.att_sessions_to_date, s.att_rate_to_date FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN trainings tr ON tr.id=t.training_id JOIN training_sites st ON st.id=t.site_id JOIN training_classes k ON k.id=t.class_id WHERE t.project_id=? AND t.roster_status IN ('active','reserve') AND ${s.sql} ${p.providerId ? "AND t.provider_id=?" : ""} ${p.classId ? "AND t.class_id=?" : ""} ORDER BY p.code, tr.title, k.code, t.trainee_code`, [c.pid, ...s.args, ...(p.providerId ? [p.providerId] : []), ...(p.classId ? [p.classId] : [])] as never[])); } },
  { key: "attendance_coverage", title: "Attendance coverage", description: "Session days recorded and due, by provider and any breakdown.", formats: ALL, params: ["provider"], perm: "attendance.view", build: async (c, p) => { const r = coverageBy(await coverage(c, p.providerId), (p.dims ?? "").split(",").filter(Boolean)); return { title: "Attendance coverage", subtitle: await sub(c), sections: [{ title: "Session days", header: r.header, rows: r.rows }] }; } },
  { key: "dropout_monitoring", title: "Dropout monitoring", description: "Trainees at risk, below 80 %, or reported as dropouts.", formats: ["xlsx", "csv", "pdf"], params: ["provider"], perm: "outcome.view", build: async (c, p) => { const s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" }); return table(c, "Dropout monitoring", ["Provider", "Class", "Trainee ID", "Name", "Rate %", "Highest reachable %", "Final %", "At risk", "Below 80 % at the end", "Reported by provider", "Reason"], await query(pool, `SELECT p.code, k.code AS cls, t.trainee_code, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, s.att_rate_to_date, s.att_max_reachable, s.att_rate_final, IF(s.system_dropout_risk,'Yes','No') AS a, IF(s.system_dropout_final,'Yes','No') AS b, s.dropout_status, s.dropout_reason FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN training_classes k ON k.id=t.class_id WHERE t.project_id=? AND t.roster_status IN ('active','reserve') AND (s.system_dropout_risk OR s.system_dropout_final OR s.dropout_status='yes') ${c.access.providerId ? "AND (s.system_dropout_final OR s.dropout_status='yes')" : ""} AND ${s.sql} ${p.providerId ? "AND t.provider_id=?" : ""} ORDER BY p.code, k.code, t.trainee_code`, [c.pid, ...s.args, ...(p.providerId ? [p.providerId] : [])] as never[])); } },
  { key: "outcome_status", title: "Outcome status per trainee", description: "Every trainee's result for every report.", formats: ["xlsx", "csv"], params: ["provider", "class"], perm: "outcome.view", build: async (c, p) => { const s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" }); return table(c, "Outcome status", ["Provider", "Class", "Trainee ID", "Name", "Dropout", "Completion", "Certification", "Employment placement", "Locality", "Retention 3 m"], await query(pool, `SELECT p.code, k.code AS cls, t.trainee_code, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, s.dropout_status, s.completion_status, s.certification_status, s.placement_status, s.locality_status, s.retention_3m_status FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN training_classes k ON k.id=t.class_id WHERE t.project_id=? AND t.roster_status IN ('active','reserve') AND ${s.sql} ${p.providerId ? "AND t.provider_id=?" : ""} ${p.classId ? "AND t.class_id=?" : ""} ORDER BY p.code, k.code, t.trainee_code`, [c.pid, ...s.args, ...(p.providerId ? [p.providerId] : []), ...(p.classId ? [p.classId] : [])] as never[])); } },
  { key: "possible_duplicates", title: "Possible duplicates", description: "Pairs of trainees that look like the same person.", formats: ["xlsx", "csv"], params: [], perm: "duplicate.review", build: async (c) => table(c, "Possible duplicates", ["Score", "Status", "Trainee A", "Name A", "Provider A", "Trainee B", "Name B", "Provider B"], await query(pool, "SELECT d.score, d.status, a.trainee_code AS ca, CONCAT_WS(' ',a.first_name,a.father_name,a.grandfather_name) AS na, pa.code AS pa, b.trainee_code AS cb, CONCAT_WS(' ',b.first_name,b.father_name,b.grandfather_name) AS nb, pb.code AS pb FROM duplicate_candidates d JOIN trainees a ON a.id=d.trainee_a_id JOIN trainees b ON b.id=d.trainee_b_id JOIN providers pa ON pa.id=a.provider_id JOIN providers pb ON pb.id=b.provider_id WHERE a.project_id=? ORDER BY d.score DESC", [c.pid])) },
  { key: "registration_changes", title: "Registration changes", description: "Trainees added, withdrawn or changed, with who did it and when.", formats: ["xlsx", "csv"], params: ["provider", "period"], perm: "trainee.view_pii", build: async (c, p) => { const s = S(c, "t.provider_id", p); return table(c, "Registration changes", ["When", "Who", "What", "Trainee ID", "Name", "Provider", "Roster now"], await query(pool, `SELECT e.occurred_at, COALESCE(u.name,'System') AS who, e.summary, t.trainee_code, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, p.code, t.roster_status FROM audit_events e JOIN trainees t ON t.id=e.entity_id JOIN providers p ON p.id=t.provider_id LEFT JOIN users u ON u.id=e.actor_user_id WHERE e.project_id=? AND e.entity_type='trainee' AND ${s.sql} ${p.period ? "AND DATE_FORMAT(e.occurred_at,'%Y-%m')=?" : ""} ORDER BY e.id DESC LIMIT 20000`, [c.pid, ...s.args, ...(p.period ? [p.period] : [])])); } },
];
