import { chromium } from "playwright-core";
import { resolveBrowserPath } from "./diagram-renderer.js";
import { puterChatComplete } from "../puter-inference.js";
import type { RenderResult, PdfDocumentBundle } from "./types.js";

// ─── Markdown fence stripper ─────────────────────────────────────────────────

function stripMarkdownFences(raw: string): string {
  return raw
    .trim()
    .replace(/^```(?:html)?\s*/i, "")
    .replace(/\s*```$/, "")
    .trim();
}

// ─── System prompt builder ───────────────────────────────────────────────────

export function buildPdfSystemPrompt(docType: string): string {
  const baseConstraints = [
    "Output ONLY a complete HTML document starting with <!DOCTYPE html>.",
    "Use only inline CSS in a <style> block. No external URLs, no <link> tags, no <script> tags.",
    "Use web-safe system fonts: Arial, Georgia, monospace.",
    "The document must be print-ready and visually professional.",
  ].join("\n");

  switch (docType) {
    case "invoice":
      return [
        "You are an HTML invoice generator.",
        "Create a professional invoice with: company header, invoice number, date, bill-to section, line items table (description, quantity, unit price, total), subtotal, tax, and grand total.",
        "Use a clean business layout with a muted color palette.",
        baseConstraints,
      ].join("\n");

    case "api-docs":
      return [
        "You are an HTML API documentation generator.",
        "Create well-structured API reference documentation with: overview section, endpoint listings with HTTP method badges, request/response examples in monospace blocks, parameter tables, and status code descriptions.",
        "Use a technical documentation style with good code block formatting.",
        baseConstraints,
      ].join("\n");

    case "one-pager":
      return [
        "You are an HTML one-pager generator.",
        "Create a compelling single-page document with: a bold headline, value proposition, key benefits or features in a grid or list, supporting details, and a clear call-to-action.",
        "Use a modern, visually impactful layout with strong typography hierarchy.",
        baseConstraints,
      ].join("\n");

    case "report":
    default:
      return [
        "You are an HTML report generator.",
        "Create a professional report with: a title page section, executive summary, clearly delineated sections with headings and subheadings, data presentation areas (tables or structured lists), and a conclusion.",
        "Use a formal report layout with clear section separation and consistent typography.",
        baseConstraints,
      ].join("\n");
  }
}

// ─── Main renderer ───────────────────────────────────────────────────────────

export async function renderPdfDocument(
  input: Record<string, unknown>,
): Promise<RenderResult> {
  const docType =
    typeof input.docType === "string" ? input.docType : "report";
  const prompt =
    typeof input.prompt === "string" ? input.prompt : "";
  const title =
    typeof input.title === "string" ? input.title : "Document";

  // ── LLM HTML generation ────────────────────────────────────────────────────
  const systemPrompt = buildPdfSystemPrompt(docType);
  const rawHtml = await puterChatComplete([
    { role: "system", content: systemPrompt },
    { role: "user", content: prompt },
  ]);
  const html = stripMarkdownFences(rawHtml);

  // ── Playwright HTML-to-PDF ─────────────────────────────────────────────────
  const executablePath = resolveBrowserPath();
  const browser = await chromium.launch({
    executablePath,
    headless: true,
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });

  let pdfBuffer: Buffer;
  try {
    const page = await browser.newPage();
    await page.setContent(html, { waitUntil: "networkidle" });
    const pdfUint8 = await page.pdf({
      format: "A4",
      printBackground: true,
      margin: { top: "20mm", bottom: "20mm", left: "20mm", right: "20mm" },
    });
    pdfBuffer = Buffer.from(pdfUint8);
  } finally {
    await browser.close();
  }

  // ── Build bundle ───────────────────────────────────────────────────────────
  const bundle: PdfDocumentBundle = {
    type: "pdf-document-bundle",
    docType,
    title,
    pdfBase64: pdfBuffer.toString("base64"),
  };

  return {
    filename: `document-${docType}.json`,
    contentType: "application/json",
    buffer: Buffer.from(JSON.stringify(bundle)),
  };
}
