import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { jsPDF } from 'npm:jspdf@4.0.0';

Deno.serve(async (req) => {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json().catch(() => ({}));
    const {
      taskName = 'Untitled task',
      date = new Date().toISOString().slice(0, 10),
      summary = '',
      sections = [], // [{ heading, body }]
      footer = 'LimbForge · CoverCanvas — generated handover'
    } = body || {};

    if (!summary && sections.length === 0) {
      return Response.json({ error: 'summary or sections required' }, { status: 400 });
    }

    const doc = new jsPDF({ unit: 'pt', format: 'a4' });
    const pageW = doc.internal.pageSize.getWidth();
    const pageH = doc.internal.pageSize.getHeight();
    const margin = 48;
    const contentW = pageW - margin * 2;
    let y = margin;

    const ensure = (needed) => {
      if (y + needed > pageH - margin) { doc.addPage(); y = margin; }
    };

    // Header band
    doc.setFillColor(10, 13, 18);
    doc.rect(0, 0, pageW, 96, 'F');
    doc.setFillColor(34, 211, 238);
    doc.rect(margin, 40, 4, 36, 'F');
    doc.setTextColor(34, 211, 238);
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(11);
    doc.text('LIMBFORGE · HANDOVER', margin + 16, 54);
    doc.setTextColor(230, 240, 245);
    doc.setFontSize(17);
    doc.text(String(taskName).slice(0, 80), margin + 16, 74);

    y = 120;
    doc.setTextColor(120, 140, 155);
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(9);
    doc.text(`Date: ${date}`, margin, y);
    doc.text(`Prepared by: ${user.full_name || user.email || 'Base44 agent'}`, margin + 220, y);
    y += 18;

    // Divider
    doc.setDrawColor(34, 211, 238);
    doc.setLineWidth(0.8);
    doc.line(margin, y, pageW - margin, y);
    y += 20;

    if (summary) {
      ensure(40);
      doc.setTextColor(20, 26, 33);
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(12);
      doc.text('Summary', margin, y);
      y += 16;
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(10);
      doc.setTextColor(45, 55, 66);
      const lines = doc.splitTextToSize(String(summary), contentW);
      for (const ln of lines) { ensure(16); doc.text(ln, margin, y); y += 14; }
      y += 10;
    }

    for (const sec of sections) {
      const heading = sec.heading || '';
      const body = Array.isArray(sec.body) ? sec.body.join('\n') : String(sec.body || '');
      ensure(40);
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(12);
      doc.setTextColor(20, 26, 33);
      doc.text(heading, margin, y);
      y += 16;
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(10);
      doc.setTextColor(45, 55, 66);
      for (const paragraph of String(body).split('\n')) {
        const lines = doc.splitTextToSize(paragraph, contentW);
        for (const ln of lines) {
          ensure(16);
          doc.text(ln, margin, y);
          y += 14;
        }
        y += 4;
      }
      y += 8;
    }

    // Footer on every page
    const pages = doc.getNumberOfPages();
    for (let i = 1; i <= pages; i++) {
      doc.setPage(i);
      doc.setDrawColor(220, 225, 230);
      doc.setLineWidth(0.5);
      doc.line(margin, pageH - 30, pageW - margin, pageH - 30);
      doc.setFont('helvetica', 'normal');
      doc.setFontSize(8);
      doc.setTextColor(140, 150, 160);
      doc.text(footer, margin, pageH - 18);
      doc.text(`Page ${i} / ${pages}`, pageW - margin - 60, pageH - 18);
    }

    const pdfBytes = doc.output('arraybuffer');
    const stamp = Date.now();
    const filename = `handover-${String(taskName).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40)}-${stamp}.pdf`;
    const file = new File([pdfBytes], filename, { type: 'application/pdf' });

    const up = await base44.asServiceRole.integrations.Core.UploadPrivateFile({ file });
    const signed = await base44.asServiceRole.integrations.Core.CreateFileSignedUrl({
      file_uri: up.file_uri,
      expires_in: 86400
    });

    return Response.json({
      signed_url: signed.signed_url,
      file_uri: up.file_uri,
      filename,
      pages,
      prepared_by: user.full_name || user.email || 'Base44 agent'
    });
  } catch (error) {
    return Response.json({ error: error.message }, { status: 500 });
  }
});