import { IndexPlanRowSchema, PlanStatusSchema, type IndexPlanRow } from "./schema";

const LINK_RE = /^\[([^\]]+)\]\(([^)]+)\)$/;

function parseStatus(raw: string): IndexPlanRow["status"] | null {
  const token = raw.trim().split(/\s+/)[0]?.toUpperCase();
  const parsed = PlanStatusSchema.safeParse(token);
  return parsed.success ? parsed.data : null;
}

function parsePlanCell(cell: string): { title: string; href: string } | null {
  const trimmed = cell.trim();
  const match = LINK_RE.exec(trimmed);
  if (!match) return null;
  return { title: match[1]!, href: match[2]! };
}

export function parsePlanIndexTable(markdown: string): IndexPlanRow[] {
  const rows: IndexPlanRow[] = [];
  for (const line of markdown.split(/\r?\n/)) {
    if (!line.startsWith("|")) continue;
    if (line.includes("---|")) continue;
    const cells = line
      .split("|")
      .slice(1, -1)
      .map((cell) => cell.trim());
    if (cells.length < 5) continue;
    if (cells[0] === "Priority" || cells[1] === "Status") continue;

    const status = parseStatus(cells[1] ?? "");
    const plan = parsePlanCell(cells[2] ?? "");
    if (!status || !plan) continue;

    const parsed = IndexPlanRowSchema.safeParse({
      priority: cells[0],
      status,
      title: plan.title,
      href: plan.href,
      scope: cells[3] ?? "",
      indexReceipt: cells[4] ?? "",
    });
    if (parsed.success) rows.push(parsed.data);
  }
  return rows;
}
