import { PlanFrontmatterSchema, type PlanFrontmatter } from "./schema";

function sectionValue(markdown: string, heading: string): string | undefined {
  const pattern = new RegExp(`^## ${heading}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`, "m");
  const match = pattern.exec(markdown);
  if (!match) return undefined;
  const body = match[1]?.trim() ?? "";
  return body.length > 0 ? body : undefined;
}

function frontmatterValue(markdown: string, key: string): string | undefined {
  const pattern = new RegExp(`^${key}:\\s*(.+)$`, "im");
  const match = pattern.exec(markdown);
  if (!match) return undefined;
  return match[1]?.trim();
}

export function parsePlanFrontmatter(markdown: string): PlanFrontmatter {
  const status = frontmatterValue(markdown, "status") ?? "unknown";
  const worker = frontmatterValue(markdown, "worker");
  const taskIds = frontmatterValue(markdown, "task IDs");
  const planReceipt = sectionValue(markdown, "Current receipt");
  const nextAction = sectionValue(markdown, "Next executable action");

  return PlanFrontmatterSchema.parse({
    status,
    ...(worker ? { worker } : {}),
    ...(taskIds ? { taskIds } : {}),
    ...(planReceipt ? { planReceipt } : {}),
    ...(nextAction ? { nextAction } : {}),
  });
}

export function normalizeFileStatus(status: string): string {
  return status.trim().split(/\s+/)[0]?.toUpperCase() ?? status.trim().toUpperCase();
}
