import { readFileSync } from "node:fs";
import { join } from "node:path";
import type { Connection, ResultSetHeader, RowDataPacket } from "mysql2/promise";

interface Entry { no: number; code: string; name: string; operationalDefinition: string; dataSources: string; frequency: string; computation: string; disaggregations: string[]; target: string }
/** Official texts of all 19 indicators, taken from "Indicator protocols (Draft).docx". V1's names, formulas and thresholds are not changed. */
export default async function protocol(db: Connection): Promise<number> {
  const all = JSON.parse(readFileSync(join(import.meta.dirname, "../data/indicator-protocol.json"), "utf8")) as Entry[];
  // V1 since 2026-12-03 holds job linkage already renamed to employment placement, and decent job switched off (step 58 removes it).
  const [m] = await db.query<RowDataPacket[]>("SELECT 1 FROM indicator_definitions WHERE code='employment_placement_rate' LIMIT 1"), merged = m.length > 0;
  const codes = (c: string) => (merged && c === "job_linkage_rate" ? ["employment_placement_rate"] : [c]);
  let n = 0;
  for (const e of all) {
    const [r] = await db.query<ResultSetHeader>("UPDATE indicator_definitions SET protocol_no=?, operational_definition=?, data_sources=?, frequency=?, computation_text=?, disaggregations_json=?, name=IF(level='provider',?,name) WHERE code IN (?) AND status='active'",
      [e.no, e.operationalDefinition, e.dataSources, e.frequency, e.computation, JSON.stringify(e.disaggregations), e.name.replace(/\s+/g, " ").slice(0, 250), codes(e.code)]);
    n += r.affectedRows;
  }
  const want = merged ? 18 : 19;
  if (n < want) throw new Error(`Only ${n} of ${want} protocol indicators exist.`);
  return n;
}
