import { audit } from "../../core/audit/audit.js";
import { execute, insert, insertMany, json, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { readTable, toCsv, toXlsx } from "../../core/files/table.js";
import { can, classInScope, conflict, invalid, notFound, scope, type Ctx } from "../../core/http/route.js";
import { DomainError } from "../../core/http/errors.js";
import { cached } from "../../core/cache.js";
import { dmy, addDays, diffDays, isDate, parseFormDate, today } from "../../shared/dates.js";
import { allClasses, calendarDays, getClassView, rate, recomputeClass } from "../delivery/index.js";
import { queueKpis } from "../projects/index.js";
import { traineeRows } from "../registration/index.js";

/** Only present or absent can be recorded. "E" is kept for marks that V1 may hold. */
type Mark = "P" | "A" | "E";
const CODE: Record<Mark, number> = { P: 1, A: 2, E: 3 }, MARK: Record<number, Mark> = { 1: "P", 2: "A", 3: "E" };
const lateDays = async (pid: string) => Number((await one(pool, "SELECT late_attendance_days AS d FROM projects WHERE id=?", [pid]))!["d"]);
/** Trainees who must have a mark on a date: tracked, and already attending by then. */
const roster = (db: Db, classId: string, date: string) => query(db, "SELECT id, trainee_code, CONCAT_WS(' ',first_name,father_name,grandfather_name) AS name FROM trainees WHERE class_id=? AND roster_status IN ('active','reserve') AND (attendance_eligible_from IS NULL OR attendance_eligible_from<=?) ORDER BY trainee_code", [classId, date]);
const missingDates = async (classId: string) => (await query(pool, "SELECT d.cal_date AS d FROM class_calendar_days d LEFT JOIN attendance_sessions s ON s.class_id=d.class_id AND s.session_date=d.cal_date WHERE d.class_id=? AND d.kind='session' AND d.cal_date<=? AND s.id IS NULL ORDER BY d.cal_date", [classId, today()])).map((x) => x["d"] as string);

export async function todo(c: Ctx) {
  const classes = (await allClasses(c)).filter((x) => x.status !== "cancelled" && x.status !== "planned"), due1 = classes.filter((x) => x.sessionsMissing > 0), all = due1.length ? await query(pool, "SELECT d.class_id, d.cal_date AS d FROM class_calendar_days d LEFT JOIN attendance_sessions s ON s.class_id=d.class_id AND s.session_date=d.cal_date WHERE d.class_id IN (?) AND d.kind='session' AND d.cal_date<=? AND s.id IS NULL ORDER BY d.cal_date", [due1.map((x) => x.id as string), today()]) : [], dates = new Map<string, string[]>();
  for (const m of all) dates.set(m["class_id"], [...(dates.get(m["class_id"]) ?? []), m["d"]]);
  const out = due1.map((cls) => ({ cls, dates: dates.get(cls.id) ?? [] }));
  const s = scope(c, { provider: "c.provider_id", cls: "c.id", site: "c.site_id" });
  const t = (await one(pool, `SELECT SUM(k.att_present) AS p, SUM(k.att_possible) AS d, SUM(k.at_risk) AS r FROM training_classes c JOIN class_counters k ON k.class_id=c.id WHERE c.project_id=? AND ${s.sql}`, [c.pid, ...s.args] as never[]))!;
  const done = classes.reduce((a, x) => a + x.sessionsToDate - x.sessionsMissing, 0), due = classes.reduce((a, x) => a + x.sessionsToDate, 0);
  return { todo: out, classes, lateDays: await lateDays(c.pid), today: today(), summary: { rate: rate(t["p"], t["d"]), coverage: rate(done, due), missing: due - done, atRisk: t["r"] ?? 0 } };
}
export async function sheet(c: Ctx, classId: string, wanted?: string) {
  const cls = await getClassView(c, classId), calendar = await calendarDays(classId), missing = await missingDates(classId), now = today();
  const sessionDates = calendar.filter((d) => d.kind === "session" && d.date <= now).map((d) => d.date);
  const date = wanted && isDate(wanted) && sessionDates.includes(wanted) ? wanted : missing[0] ?? sessionDates.at(-1);
  const session = date ? await one(pool, "SELECT s.id, s.submitted_at, u.name FROM attendance_sessions s LEFT JOIN users u ON u.id=s.submitted_by WHERE s.class_id=? AND s.session_date=?", [classId, date]) : undefined;
  const marks = session ? await query(pool, "SELECT trainee_id, status FROM attendance_marks WHERE session_id=?", [session["id"]]) : [];
  const labels = await dayLabels(pool, await classInScope(c, classId)), taken = new Set((await query(pool, "SELECT session_date AS d FROM attendance_sessions WHERE class_id=?", [classId])).map((x) => x["d"] as string)), full = calendar.map((d) => ({ ...d, ...(["holiday", "breakdown"].includes(d.kind) && labels.get(d.date) ? { label: labels.get(d.date) } : {}), ...(d.kind === "session" && d.date <= now ? { attendance: taken.has(d.date) ? "present" : "missing" } : {}) }));
  const why = wanted && wanted !== date ? await assertSession(pool, await classInScope(c, classId), wanted).then(() => undefined, (e: Error) => dmy(e.message)) : undefined;
  const waiting = (await query(pool, "SELECT session_date AS d FROM attendance_late_requests WHERE class_id=? AND status='requested'", [classId])).map((x) => x["d"] as string);
  return { cls, calendar: full, waiting, notSession: why, lateApproval: Boolean((await one(pool, "SELECT late_attendance_approval AS a FROM projects WHERE id=?", [c.pid]))!["a"]), sessionDates, missing, date, ...(session ? { submitted: { by: session["name"] ?? "", at: session["submitted_at"] } } : {}), roster: await traineeRows(c, "t.class_id=? AND t.roster_status IN ('active','reserve')", [classId]), marks: Object.fromEntries(marks.map((m) => [m["trainee_id"], MARK[m["status"]]])), lateDays: await lateDays(c.pid), today: now, requestedDate: wanted };
}
/** Says exactly why a day takes no attendance: holiday, breakdown, first days of the class, or simply no class that day. */
async function assertSession(db: Db, cls: Row, date: string): Promise<void> {
  const day = await one(db, "SELECT kind FROM class_calendar_days WHERE class_id=? AND cal_date=?", [cls["id"], date]), kind = day?.["kind"] as string | undefined;
  if (kind === "session") return;
  const label = (await dayLabels(db, cls)).get(date), why: Record<string, string> = { holiday: `${date} is a holiday${label ? ` (${label})` : ""}`, breakdown: `${date} is inside an approved breakdown${label ? ` (${label})` : ""}`, exempt: `${date} is in the first days of the class, which are not counted`, non_session: `The class does not meet on ${date}` };
  throw new DomainError(422, "NOT_A_SESSION", `${why[kind ?? ""] ?? `${date} is outside the dates of this class`}, so no attendance is recorded.`);
}
/** Names of the holidays and breakdowns of a class, by date. */
async function dayLabels(db: Db, cls: Row): Promise<Map<string, string>> {
  const out = new Map<string, string>();
  for (const b of await query(db, "SELECT start_date AS s, end_date AS e, reason FROM training_breakdowns WHERE status='approved' AND training_id=? AND (class_id=? OR (class_id IS NULL AND (site_id=? OR site_id IS NULL)))", [cls["training_id"], cls["id"], cls["site_id"]])) for (let d = b["s"] as string; d <= b["e"]; d = addDays(d, 1)) out.set(d, b["reason"] ?? "Breakdown");
  for (const h of await query(db, "SELECT holiday_date AS d, label FROM holidays WHERE project_id=? AND (location_id IS NULL OR location_id=(SELECT location_id FROM training_sites WHERE id=?))", [cls["project_id"], cls["site_id"]])) out.set(h["d"], h["label"]);
  return out;
}
export async function saveSession(db: Db, c: Ctx, cls: Row, date: string, marks: Record<string, Mark>, o: { reasons?: Record<string, string> | undefined; justification?: string | undefined; source?: string; by?: string } = {}): Promise<{ added: number; backfill: boolean }> {
  await assertSession(db, cls, date);
  if (date > today()) throw new DomainError(422, "FUTURE_DATE", "Attendance cannot be recorded for a future date.");
  if (diffDays(date, today()) > (await lateDays(c.pid)) && !o.justification?.trim()) invalid("justification", "Explain why this attendance is late.");
  await one(db, "SELECT id FROM training_classes WHERE id=? FOR UPDATE", [cls["id"]]);
  const people = await roster(db, cls["id"], date), session = await one(db, "SELECT id FROM attendance_sessions WHERE class_id=? AND session_date=?", [cls["id"], date]);
  const already = new Set(session ? (await query(db, "SELECT trainee_id FROM attendance_marks WHERE session_id=?", [session["id"]])).map((m) => String(m["trainee_id"])) : []);
  const need = people.filter((p) => !already.has(p["id"])), known = new Set(people.map((p) => p["id"]));
  if (session && !need.length) conflict("ALREADY_SUBMITTED", `Attendance of ${date} is already submitted. Request a correction to change it.`);
  const errors = [...need.filter((p) => !marks[p["id"]]).map((p) => ({ path: `marks.${p["id"]}`, code: "REQUIRED", message: `${p["name"]} has no mark.` })), ...Object.keys(marks).filter((t) => !known.has(t)).map((t) => ({ path: `marks.${t}`, code: "NOT_IN_CLASS", message: "This trainee is not in the class on that date." }))];
  if (errors.length) throw new DomainError(422, "INCOMPLETE", "Every trainee needs one mark.", errors.slice(0, 50));
  const sid = session?.["id"] ?? (await insert(db, "attendance_sessions", { project_id: c.pid, provider_id: cls["provider_id"], class_id: cls["id"], session_date: date, status: "submitted", source: o.source ?? "manual", submitted_by: o.by ?? c.user.id, submitted_at: new Date().toISOString().slice(0, 23).replace("T", " ") }));
  await insertMany(db, "attendance_marks", ["session_id", "trainee_id", "status", "reason_code", "is_backfill", "marked_at"], need.map((p) => [sid, p["id"], CODE[marks[p["id"]]!], o.reasons?.[p["id"]]?.slice(0, 40) ?? null, session ? 1 : 0, new Date().toISOString().slice(0, 23).replace("T", " ")]));
  await recount(db, sid);
  await audit(db, c, { module: "attendance", action: session ? "backfill" : "submitted", entityType: "attendance_session", entityId: String(sid), providerId: cls["provider_id"], summary: `Attendance ${cls["code"]} ${date}: ${need.length} marks`, after: { date, marks: Object.fromEntries(need.map((p) => [p["id"], marks[p["id"]]])), justification: o.justification } });
  return { added: need.length, backfill: Boolean(session) };
}
const recount = (db: Db, sid: string) => execute(db, "UPDATE attendance_sessions s JOIN (SELECT session_id, COUNT(*) AS n, SUM(status=1) AS p, SUM(status=2) AS a, SUM(status=3) AS e FROM attendance_marks WHERE session_id=? GROUP BY session_id) k ON k.session_id=s.id SET s.marks_count=k.n, s.present_count=k.p, s.absent_count=k.a, s.excused_count=k.e", [sid]);
/** Saves the day, or keeps it for M&E when the project asks for approval of late attendance. */
async function record(c: Ctx, cls: Row, date: string, marks: Record<string, Mark>, o: { justification?: string | undefined; source?: string }) {
  const p = (await one(pool, "SELECT late_attendance_days AS d, late_attendance_approval AS a FROM projects WHERE id=?", [c.pid]))!;
  return transaction(async (tx) => {
    const r = await saveSession(tx, c, cls, date, marks, o);
    if (p["a"] && diffDays(date, today()) > p["d"]) { throw new Held(r.added); }
    await recomputeClass(tx, cls["id"]);
    await queueKpis(tx, c.pid);
    return { ok: true, sessions: 1, marks: r.added, waiting: false };
  }).catch(async (e: unknown) => {
    // Everything was checked, then rolled back: the marks wait for a decision instead.
    if (!(e instanceof Held)) throw e;
    if (await one(pool, "SELECT 1 AS x FROM attendance_late_requests WHERE class_id=? AND session_date=? AND status='requested'", [cls["id"], date])) conflict("ALREADY_REQUESTED", "This day is already waiting for approval.");
    await transaction(async (tx) => { const id = await insert(tx, "attendance_late_requests", { project_id: c.pid, class_id: cls["id"], session_date: date, marks_json: JSON.stringify(marks), justification: (o.justification ?? "").slice(0, 490), source: o.source ?? "manual", requested_by: c.user.id }); await audit(tx, c, { module: "attendance", action: "late_requested", entityType: "attendance_late", entityId: id, providerId: cls["provider_id"], summary: `Late attendance ${cls["code"]} ${date} waits for approval` }); });
    return { ok: true, sessions: 0, marks: e.added, waiting: true };
  });
}
class Held extends Error { constructor(readonly added: number) { super("held"); } }
export async function submit(c: Ctx, classId: string, date: string, b: { marks: Record<string, Mark>; justification?: string | undefined }) {
  const cls = await classInScope(c, classId);
  if (!isDate(date)) notFound("Date");
  return record(c, cls, date, b.marks, b);
}
const LATE = "SELECT q.*, k.code AS classCode, k.provider_id, p.code AS providerCode, u.name AS who FROM attendance_late_requests q JOIN training_classes k ON k.id=q.class_id JOIN providers p ON p.id=k.provider_id LEFT JOIN users u ON u.id=q.requested_by";
const lateView = (x: Row) => { const m = Object.values(json<Record<string, string>>(x["marks_json"], {})); return { id: x["id"], classId: x["class_id"], classCode: x["classCode"], providerCode: x["providerCode"], date: x["session_date"], present: m.filter((v) => v === "P").length, absent: m.filter((v) => v === "A").length, reason: x["justification"], status: x["status"], requestedBy: x["who"] ?? "", requestedAt: x["requested_at"], decisionNote: x["decision_note"] ?? undefined }; };
export async function lateRequests(c: Ctx) { const s = scope(c, { provider: "k.provider_id", cls: "k.id", site: "k.site_id" }); return (await query(pool, `${LATE} WHERE q.project_id=? AND ${s.sql} ORDER BY q.status='requested' DESC, q.id DESC LIMIT 300`, [c.pid, ...s.args] as never[])).map(lateView); }
export async function decideLate(c: Ctx, id: string, decision: "approve" | "reject", note: string) {
  const x = (await one(pool, `${LATE} WHERE q.id=? AND q.project_id=?`, [id, c.pid])) ?? notFound("Request"), cls = (await one(pool, "SELECT * FROM training_classes WHERE id=?", [x["class_id"]]))!;
  if (decision === "reject" && !note.trim()) invalid("note", "Write a note before you reject.");
  await transaction(async (tx) => {
    if (!(await execute(tx, "UPDATE attendance_late_requests SET status=?, decided_by=?, decided_at=UTC_TIMESTAMP(3), decision_note=? WHERE id=? AND status='requested'", [decision === "approve" ? "approved" : "rejected", c.user.id, note, id])).affectedRows) conflict("ALREADY_DECIDED", "This is already decided.");
    if (decision === "approve") { await saveSession(tx, c, cls, x["session_date"], json(x["marks_json"], {}), { justification: x["justification"], source: x["source"], by: x["requested_by"] }); await recomputeClass(tx, cls["id"]); await queueKpis(tx, c.pid); }
    await audit(tx, c, { module: "attendance", action: `late_${decision}`, entityType: "attendance_late", entityId: id, providerId: cls["provider_id"], summary: `Late attendance ${cls["code"]} ${x["session_date"]}: ${decision}`, after: { note } });
  });
  return lateView((await one(pool, `${LATE} WHERE q.id=?`, [id]))!);
}
/** V1's template: the class list for ONE day. */
const HEADER = ["external_beneficiary_id", "trainee_unique_id", "trainee_name", "roster_role", "session_date", "status", "cohort", "delivery_batch"];
export async function template(c: Ctx, classId: string, date: string | undefined, format: string) {
  const cls = await classInScope(c, classId), d = date && isDate(date) ? date : invalid("date", "Choose the session day first.");
  await assertSession(pool, cls, d);
  const site = await one(pool, "SELECT l.code FROM training_sites s LEFT JOIN locations l ON l.id=s.location_id WHERE s.id=?", [cls["site_id"]]), people = await query(pool, "SELECT trainee_code, external_beneficiary_id AS ext, roster_status, CONCAT_WS(' ',first_name,father_name,grandfather_name) AS name FROM trainees WHERE id IN (?)", [[...(await roster(pool, classId, d)).map((p) => p["id"] as string), "0"]]);
  const rows = people.sort((x, y) => (x["trainee_code"] < y["trainee_code"] ? -1 : 1)).map((p) => [p["ext"] ?? "", p["trainee_code"], p["name"], p["roster_status"], d, "", site?.["code"] ?? "", cls["code"]] as string[]);
  return { name: `attendance_${cls["code"]}_${d}.${format === "xlsx" ? "xlsx" : "csv"}`, body: format === "xlsx" ? await toXlsx("Attendance", HEADER, rows, HEADER) : toCsv(HEADER, rows), xlsx: format === "xlsx" };
}
/** Reads the file of ONE day. Nothing is saved while any row is wrong, or when a row belongs to another day. */
export async function importFile(c: Ctx, classId: string, date: string, name: string, data: Buffer, justification?: string) {
  const cls = await classInScope(c, classId), { header, rows } = await readTable(name, data), idCol = ["trainee_unique_id", "trainee_id"].find((h) => header.includes(h));
  if (!isDate(date)) invalid("date", "Choose the session day first.");
  if (!idCol || !header.includes("session_date") || !header.includes("status")) throw new DomainError(422, "HEADER", "Use the template of this day: it needs trainee_unique_id, session_date and status.");
  if (!rows.length) throw new DomainError(422, "FILE_EMPTY", "The file has no rows.");
  const people = await query(pool, "SELECT id, trainee_code, external_beneficiary_id AS ext FROM trainees WHERE class_id=?", [classId]), byCode = new Map(people.map((p) => [String(p["trainee_code"]).toUpperCase(), p["id"] as string])), byExt = new Map(people.filter((p) => p["ext"]).map((p) => [String(p["ext"]).toUpperCase(), p["id"] as string]));
  const marks: Record<string, Mark> = {}, bad: { path: string; code: string; message: string }[] = [];
  const toMark = (v: string): Mark | undefined => ({ P: "P", PRESENT: "P", "1": "P", A: "A", ABSENT: "A", "0": "A" })[v.trim().toUpperCase()] as Mark | undefined;
  for (const [i, x] of rows.entries()) {
    const code = (x[idCol] ?? "").trim(), id = byCode.get(code.toUpperCase()) ?? byExt.get((x["external_beneficiary_id"] ?? "").trim().toUpperCase()), d = parseFormDate(x["session_date"] ?? ""), m = toMark(x["status"] ?? "");
    const issue = !id ? "This trainee is not in the class." : d !== date ? `This row is for ${x["session_date"] || "no day"}. One file holds one day: ${date}.` : !m ? "Write present or absent." : marks[id] ? "This trainee appears twice." : undefined;
    if (issue) bad.push({ path: `Row ${i + 2} ${code}`, code: "CELL", message: issue }); else marks[id!] = m!;
  }
  if (bad.length) throw new DomainError(422, "FILE_HAS_ERRORS", `${bad.length} rows need attention. Nothing was saved.`, bad.slice(0, 100));
  return record(c, cls, date, marks, { justification: justification?.trim() || `File: ${name}`, source: "csv" });
}
const COR = `SELECT x.*, s.class_id, s.session_date, k.code AS classCode, k.provider_id, CONCAT_WS(' ',t.first_name,t.father_name) AS traineeName, u.name AS requestedName FROM attendance_corrections x JOIN attendance_sessions s ON s.id=x.session_id JOIN training_classes k ON k.id=s.class_id JOIN trainees t ON t.id=x.trainee_id LEFT JOIN users u ON u.id=x.requested_by`;
const corView = (x: Row) => ({ id: x["id"], classId: x["class_id"], classCode: x["classCode"], date: x["session_date"], traineeId: x["trainee_id"], traineeName: x["traineeName"], from: MARK[x["from_status"]], to: MARK[x["to_status"]], reason: x["reason"], status: x["status"], requestedBy: x["requestedName"] ?? "", requestedAt: x["requested_at"], decisionNote: x["decision_note"] ?? undefined });
export async function corrections(c: Ctx) {
  const s = scope(c, { provider: "k.provider_id", cls: "k.id", site: "k.site_id" });
  return (await query(pool, `${COR} WHERE s.project_id=? AND ${s.sql} ${c.query["status"] ? "AND x.status=?" : ""} ORDER BY x.id DESC LIMIT 500`, [c.pid, ...s.args, ...(c.query["status"] ? [c.query["status"]] : [])] as never[])).map(corView);
}
export async function requestCorrection(c: Ctx, b: { classId: string; date: string; traineeId: string; to: Mark; reason: string }) {
  const cls = await classInScope(c, b.classId);
  const m = (await one(pool, "SELECT m.status, s.id FROM attendance_marks m JOIN attendance_sessions s ON s.id=m.session_id WHERE s.class_id=? AND s.session_date=? AND m.trainee_id=?", [b.classId, b.date, b.traineeId])) ?? notFound("Mark");
  if (m["status"] === CODE[b.to]) invalid("to", "The mark already has this value.");
  if (await one(pool, "SELECT 1 AS x FROM attendance_corrections WHERE session_id=? AND trainee_id=? AND status='requested'", [m["id"], b.traineeId])) conflict("ALREADY_REQUESTED", "A correction of this mark is already waiting.");
  const cid = await transaction(async (tx) => {
    const id = await insert(tx, "attendance_corrections", { session_id: m["id"], trainee_id: b.traineeId, from_status: m["status"], to_status: CODE[b.to], reason: b.reason, status: "requested", requested_by: c.user.id });
    await audit(tx, c, { module: "attendance", action: "correction_requested", entityType: "correction", entityId: id, providerId: cls["provider_id"], summary: `Correction ${cls["code"]} ${b.date}`, after: b });
    return id;
  });
  return corView((await one(pool, `${COR} WHERE x.id=?`, [cid]))!);
}
export async function decideCorrection(c: Ctx, cid: string, decision: "approve" | "reject", note: string) {
  const x = (await one(pool, `${COR} WHERE x.id=? AND s.project_id=?`, [cid, c.pid])) ?? notFound("Correction");
  if (decision === "reject" && !note.trim()) invalid("note", "Write a note before you reject.");
  await transaction(async (tx) => {
    if (!(await execute(tx, "UPDATE attendance_corrections SET status=?, decided_by=?, decided_at=UTC_TIMESTAMP(3), decision_note=? WHERE id=? AND status='requested'", [decision === "approve" ? "approved" : "rejected", c.user.id, note, cid])).affectedRows) conflict("ALREADY_DECIDED", "This correction is already decided.");
    if (decision === "approve") {
      await execute(tx, "UPDATE attendance_marks SET status=? WHERE session_id=? AND trainee_id=?", [x["to_status"], x["session_id"], x["trainee_id"]]);
      await execute(tx, "UPDATE attendance_sessions SET status='corrected' WHERE id=?", [x["session_id"]]);
      await recount(tx, x["session_id"]);
      await recomputeClass(tx, x["class_id"]);
      await queueKpis(tx, c.pid);
    }
    await audit(tx, c, { module: "attendance", action: `correction_${decision}`, entityType: "correction", entityId: cid, providerId: x["provider_id"], summary: `Correction ${x["classCode"]} ${x["session_date"]}: ${decision}`, before: { mark: MARK[x["from_status"]] }, after: { mark: decision === "approve" ? MARK[x["to_status"]] : MARK[x["from_status"]], note } });
  });
  return corView((await one(pool, `${COR} WHERE x.id=?`, [cid]))!);
}
export const insights = (c: Ctx) => cached(c, "attendance-insights", () => buildInsights(c));
async function buildInsights(c: Ctx) {
  const s = scope(c, { provider: "s.provider_id", cls: "s.class_id" }), extra = c.query["providerId"] ? " AND s.provider_id=?" : "", args = [c.pid, ...s.args, ...(c.query["providerId"] ? [c.query["providerId"]] : [])] as never[];
  const group = async (col: string, join = "") => (await query(pool, `SELECT ${col} AS label, SUM(s.att_present_to_date) AS p, SUM(s.att_sessions_to_date) AS d FROM trainee_status s ${join} WHERE s.project_id=? AND s.roster_status IN ('active','reserve') AND ${s.sql}${extra} GROUP BY ${col} ORDER BY ${col}`, args)).map((r) => ({ label: String(r["label"] ?? "Unknown"), rate: rate(r["p"], r["d"]) }));
  const classes = (await allClasses(c)).filter((x) => !c.query["providerId"] || x.providerId === c.query["providerId"]), codes = [...new Set(classes.map((x) => x.providerCode))];
  const byProvider = (await group("p.code", "JOIN providers p ON p.id=s.provider_id")).map((r) => { const mine = classes.filter((x) => x.providerCode === r.label), due = mine.reduce((a, x) => a + x.sessionsToDate, 0); return { code: r.label, rate: r.rate, coverage: rate(due - mine.reduce((a, x) => a + x.sessionsMissing, 0), due) }; });
  const weeks = await query(pool, `SELECT DATE_SUB(s.session_date, INTERVAL WEEKDAY(s.session_date) DAY) AS w, p.code, SUM(s.present_count+s.excused_count) AS n, SUM(s.marks_count) AS d FROM attendance_sessions s JOIN providers p ON p.id=s.provider_id WHERE s.project_id=? AND ${s.sql}${extra} AND s.session_date>=? GROUP BY w, p.code ORDER BY w`, [...args, addDays(today(), -168)] as never[]);
  const weekly: Record<string, number | string>[] = [];
  for (const w of weeks) { let row = weekly.find((x) => x["week"] === w["w"]); if (!row) weekly.push((row = { week: w["w"] })); const v = rate(w["n"], w["d"]); if (v !== undefined) row[w["code"]] = v; }
  return { byProvider, weekly, series: codes, bySex: await group("s.sex"), byLocation: await group("l.name", "LEFT JOIN locations l ON l.id=s.location_id"), byClass: classes.map((x) => ({ id: x.id, code: x.code, providerCode: x.providerCode, rate: x.attendanceRate, coverage: rate(x.sessionsToDate - x.sessionsMissing, x.sessionsToDate) ?? 0, missing: x.sessionsMissing })) };
}
export async function dailySeries(c: Ctx) {
  const s = scope(c, { provider: "s.provider_id", cls: "s.class_id" }), days = Math.min(Number(c.query["days"]) || 30, 366);
  return query(pool, `SELECT s.session_date AS date, SUM(s.present_count) AS present, SUM(s.absent_count) AS absent FROM attendance_sessions s WHERE s.project_id=? AND ${s.sql} AND s.session_date>=? GROUP BY s.session_date ORDER BY s.session_date`, [c.pid, ...s.args, addDays(today(), -days)] as never[]);
}
/** Session days due and recorded, per class. */
export async function coverage(c: Ctx, providerId?: string) {
  const s = scope(c, { provider: "c.provider_id", cls: "c.id", site: "c.site_id" });
  return query(pool, `SELECT p.code AS provider, p.name AS providerName, COALESCE(l.name,'Unassigned') AS location, t.title AS training, st.display_name AS site, c.code AS class, k.sessions_to_date AS due, k.sessions_submitted AS submitted FROM training_classes c JOIN class_counters k ON k.class_id=c.id JOIN providers p ON p.id=c.provider_id JOIN trainings t ON t.id=c.training_id JOIN training_sites st ON st.id=c.site_id LEFT JOIN locations l ON l.id=st.location_id WHERE c.project_id=? AND c.is_cancelled=0 AND ${s.sql} ${providerId ? "AND c.provider_id=?" : ""} ORDER BY p.code, t.title, c.code`, [c.pid, ...s.args, ...(providerId ? [providerId] : [])] as never[]);
}
const DIMS: Record<string, string> = { location: "Location", training: "Training", site: "Site", class: "Class" };
/** Adds the classes up to the breakdown that was asked for (V1's coverage table). */
export function coverageBy(rows: Row[], dims: string[]): { header: string[]; rows: (string | number)[][] } {
  const use = Object.keys(DIMS).filter((d) => dims.includes(d)), by = new Map<string, { keys: string[]; due: number; done: number }>();
  for (const x of rows) { const keys = [x["provider"] as string, x["providerName"] as string, ...use.map((d) => String(x[d]))], k = JSON.stringify(keys), g = by.get(k) ?? { keys, due: 0, done: 0 }; g.due += Number(x["due"] ?? 0); g.done += Number(x["submitted"] ?? 0); by.set(k, g); }
  return { header: ["Provider", "Provider name", ...use.map((d) => DIMS[d]!), "Session days recorded", "Session days due", "Missing", "Coverage %"], rows: [...by.values()].map((g) => [...g.keys, g.done, g.due, g.due - g.done, g.due ? Math.round((g.done / g.due) * 1000) / 10 : 0]) };
}
/** V1 attendance export: one row per trainee with the mark of every session, or of the chosen days. */
export async function exportClass(c: Ctx, classId: string, format: string, days: string[] = []) {
  const cls = await classInScope(c, classId), people = await query(pool, "SELECT id, trainee_code, CONCAT_WS(' ',first_name,father_name,grandfather_name) AS name FROM trainees WHERE class_id=? ORDER BY trainee_code", [classId]);
  const marks = await query(pool, "SELECT m.trainee_id, s.session_date AS d, m.status FROM attendance_marks m JOIN attendance_sessions s ON s.id=m.session_id WHERE s.class_id=?", [classId]);
  const dates = [...new Set(marks.map((m) => m["d"] as string))].filter((d) => !days.length || days.includes(d)).sort(), legacy = marks.some((m) => m["status"] === 3), kinds = (legacy ? ["P", "A", "E"] : ["P", "A"]) as Mark[], at = new Map(marks.map((m) => [`${m["trainee_id"]}:${m["d"]}`, MARK[m["status"]]!]));
  const header = ["trainee_id", "name", ...dates, "present", "absent", ...(legacy ? ["excused_v1"] : [])], rows = people.map((p) => { const v = dates.map((d) => at.get(`${p["id"]}:${d}`) ?? ""); return [p["trainee_code"], p["name"], ...v, ...kinds.map((k) => v.filter((x) => x === k).length)]; });
  return { name: `attendance_${cls["code"]}.${format === "xlsx" ? "xlsx" : "csv"}`, xlsx: format === "xlsx", body: format === "xlsx" ? await toXlsx("Attendance", header, rows) : toCsv(header, rows) };
}
export const mayDecide = (c: Ctx) => can(c, "attendance.correct.approve");
