// Deploy canary: assemble a synthetic dispatch brief against the freshly deployed
// incident assets. Exit 0 = assembly works (or assets not deployed yet — whole dir
// absent); exit 1 with the reason = deploy must fail. Run: bun scripts/brief-canary.ts
import { existsSync } from "node:fs";
import { createDeployAssetDeps } from "../src/incidents/brief-assets";
import { assembleDispatchBrief, parseTaxonomy } from "../src/incidents/dispatch-brief";
import type { Incident } from "../src/incidents/incident-service";
import { incidentAssetsDir } from "../src/paths";

function syntheticIncident(incidentType: string | null): Incident {
  return {
    id: "canary-0",
    kanboardTaskId: 0,
    title: "Deploy canary — synthetic incident",
    description: "Synthetic incident assembled at deploy time to prove the brief pipeline works against the deployed assets.",
    priority: "P2",
    incidentType,
    dispatchBrief: null,
    dispatchBriefProvenance: null,
    state: "filed",
    active: true,
    createdAt: null,
    updatedAt: null,
    resolvedAt: null,
    dispatch: {
      state: "filed",
      dispatchId: null,
      cli: null,
      model: null,
      wrapperModel: null,
      reasoningEffort: null,
      account: null,
      requestSha256: null,
      statusRevision: null,
      startedAt: null,
      heartbeatAt: null,
      completedAt: null,
      exitCode: null,
      failureClass: null,
      resultSummary: null,
    },
    activity: [],
    coverage: { stale: false },
  };
}

const assetsDir = incidentAssetsDir();
if (!existsSync(assetsDir)) {
  console.log(`brief-canary: skipped — incident assets not deployed at ${assetsDir}`);
  process.exit(0);
}

try {
  const deps = createDeployAssetDeps(assetsDir);
  const taxonomyRaw = deps.readAsset("taxonomy.json");
  const firstType = taxonomyRaw === null ? null : (parseTaxonomy(taxonomyRaw)[0]?.id ?? null);

  const typed = assembleDispatchBrief(syntheticIncident(firstType), deps);
  if (typed.text.trim() === "") {
    throw new Error("assembled brief is empty");
  }
  const untyped = assembleDispatchBrief(syntheticIncident(null), deps);
  if (untyped.text.trim() === "") {
    throw new Error("assembled untyped brief is empty");
  }

  console.log(
    `brief-canary: ok — typed(${firstType ?? "none"}): ${typed.sections.length} sections/${typed.text.length} chars, untyped: ${untyped.sections.length} sections/${untyped.text.length} chars`,
  );
} catch (error) {
  const reason = error instanceof Error ? error.message : String(error);
  console.error(`brief-canary: FAIL — ${reason} (assets: ${assetsDir})`);
  process.exit(1);
}
