import { PRODUCT_CATEGORIES } from "@/lib/design-kits/product-categories";
import { getStarterKit } from "@/lib/design-kits/registry";

const MAX_DOC_IN_PROMPT = 14_000;

function labelForProductCategory(id: unknown): string {
  if (typeof id !== "string") return String(id ?? "");
  const row = PRODUCT_CATEGORIES.find((c) => c.id === id);
  return row?.label ?? id;
}

/**
 * Human-readable block injected into AI system context so the model sees
 * everything captured in the creation wizard (build/oss/import).
 */
export function formatCreationKickoffForPrompt(
  projectData: Record<string, unknown> | null | undefined,
): string | null {
  const kickoff = projectData?.kickoff;
  if (!kickoff || typeof kickoff !== "object") return null;
  const k = kickoff as Record<string, unknown>;
  const mode = typeof k.mode === "string" ? k.mode : null;
  if (!mode) return null;

  const lines: string[] = [`### Creation wizard`, `- Mode: **${mode}**`];

  const vision = typeof k.vision === "string" ? k.vision.trim() : "";
  if (vision) lines.push(`- Initial description (productVision): ${vision}`);

  if (typeof projectData.audience === "string") {
    lines.push(`- Audience: **${projectData.audience}**`);
  }

  const sd = k.sourceData;
  if (sd && typeof sd === "object" && !Array.isArray(sd)) {
    const s = sd as Record<string, unknown>;
    if (typeof s.idea === "string" && s.idea.trim() && s.idea.trim() !== vision) {
      lines.push(`- Idea (wizard): ${s.idea.trim()}`);
    }
    if (typeof s.audience === "string") {
      lines.push(`- Audience (wizard): **${s.audience}**`);
    }
    if (typeof s.productCategory === "string") {
      lines.push(
        `- Product type: **${labelForProductCategory(s.productCategory)}** (\`${s.productCategory}\`)`,
      );
    }
    if (typeof s.designKitId === "string") {
      const kit = getStarterKit(s.designKitId);
      lines.push(
        `- Design starter: **${kit?.name ?? s.designKitId}** (\`${s.designKitId}\`)`,
      );
    }

    const doc = s.seedDocument;
    if (doc && typeof doc === "object" && !Array.isArray(doc)) {
      const d = doc as Record<string, unknown>;
      const fn = typeof d.fileName === "string" ? d.fileName : "document";
      const kind = typeof d.kind === "string" ? d.kind : "file";
      const text =
        typeof d.textExtract === "string"
          ? d.textExtract.trim()
          : "";
      if (text.length > 0) {
        const excerpt =
          text.length > MAX_DOC_IN_PROMPT
            ? `${text.slice(0, MAX_DOC_IN_PROMPT)}\n\n…[truncated for prompt length]`
            : text;
        lines.push(`\n#### Uploaded reference (${kind})\n_File: ${fn}_\n\n${excerpt}`);
      }
    }
  }

  return lines.length > 1 ? lines.join("\n") : null;
}
