// One-off seed: run with `bun scripts/seed-requests.ts` while the local collector is running.
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { loadOrCreateToken } from "../src/token";

const baseUrl = process.env.COLLECTOR_URL ?? "http://127.0.0.1:4980";
const index = readFileSync(resolve(import.meta.dir, "../../docs/plans/INDEX.md"), "utf8");
const rows = index.split("\n").filter((line) => /^\|/.test(line) && /\|\s*(ACTIVE|IDLE)\s*\|/.test(line));
let count = 0;

for (const row of rows) {
  const cells = row.split("|").slice(1, -1).map((cell) => cell.trim());
  const link = cells.find((cell) => /\[[^\]]+\]\([^)]*\.md\)/.test(cell));
  const status = cells.find((cell) => cell === "ACTIVE" || cell === "IDLE");
  if (!link || !status) continue;
  const match = /\[([^\]]+)\]\(([^)]*\.md)\)/.exec(link);
  if (!match) continue;
  const [, title, planRef] = match;
  const filename = planRef.includes("/") ? planRef.slice(planRef.lastIndexOf("/") + 1) : planRef;
  const priority = cells.find((cell) => /^(FIRE|HIGH|NORMAL|\d+)$/.test(cell));
  const scope = cells[3] ?? "";
  const date = /^(\d{4}-\d{2}-\d{2})-/.exec(filename)?.[1];
  if (!priority || !date) continue;
  const body = { id: filename.replace(/\.md$/, ""), title, project: "overdeck", state: status === "ACTIVE" ? "in_flight" : "asked", priority, asked_at: `${date}T00:00:00.000Z`, updated_at: `${date}T00:00:00.000Z`, detail: scope, plan_ref: `docs/plans/${filename}` };
  const headers = { authorization: `Bearer ${loadOrCreateToken()}`, "content-type": "application/json" };
  let response = await fetch(`${baseUrl}/requests`, { method: "POST", headers, body: JSON.stringify(body) });
  if (response.status === 409) response = await fetch(`${baseUrl}/requests/${encodeURIComponent(body.id)}`, { method: "POST", headers, body: JSON.stringify({ state: body.state, priority: body.priority, detail: body.detail, updated_at: body.updated_at }) });
  if (!response.ok) throw new Error(`${body.id}: ${response.status} ${await response.text()}`);
  console.log(`${body.id}: ${response.status === 201 ? "created" : "updated"}`);
  count += 1;
}
console.log(`seeded ${count} requests`);
