export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';

function escapeHtml(str: string): string {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function buildIntakeHtml(intake: Record<string, unknown>): string {
  const i = intake as any;
  const entities = (i.entities || []) as any[];
  const visuals = (i.visuals || []) as any[];
  const deliverables = (i.deliverables || []) as any[];
  const criteria = (i.acceptanceCriteria || []) as any[];

  const gateLabel: Record<string, string> = {
    intake_draft: 'Intake Draft',
    intake_revision: 'Intake Revision',
    intake_approved: 'Intake Approved',
    visuals_generated: 'Visuals Ready',
    visuals_revision: 'Visuals Revision',
    visuals_approved: 'Visuals Approved',
    deliverables_defined: 'Deliverables Defined',
    deliverables_revision: 'Deliverables Revision',
    deliverables_approved: 'Ready for Code Gen',
    code_generating: 'Generating Code',
    complete: 'Complete',
  };

  const listItems = (arr: string[]) => arr.map(s => `<li>${escapeHtml(s)}</li>`).join('');

  return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: 'Segoe UI', sans-serif; color: #e2e8f0; background: #0f172a; padding: 40px; }
  h1 { font-size: 24px; color: #fff; margin-bottom: 4px; }
  h2 { font-size: 16px; color: #3b82f6; margin: 24px 0 8px; border-bottom: 1px solid #1e293b; padding-bottom: 4px; }
  h3 { font-size: 13px; color: #94a3b8; margin: 12px 0 4px; }
  .meta { font-size: 12px; color: #64748b; margin-bottom: 20px; }
  .badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; }
  .badge-gate { background: #1e40af; color: #93c5fd; }
  .badge-lang { background: #065f46; color: #6ee7b7; }
  p, li { font-size: 13px; line-height: 1.6; color: #cbd5e1; }
  ul { padding-left: 20px; margin: 4px 0; }
  table { width: 100%; border-collapse: collapse; margin: 8px 0; font-size: 12px; }
  th { background: #1e293b; color: #94a3b8; text-align: left; padding: 6px 8px; font-weight: 600; }
  td { padding: 6px 8px; border-bottom: 1px solid #1e293b; color: #cbd5e1; }
  .card { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 12px; margin: 8px 0; }
  .mermaid-src { background: #0f172a; border: 1px solid #334155; border-radius: 4px; padding: 8px; font-family: monospace; font-size: 10px; white-space: pre-wrap; color: #94a3b8; overflow-wrap: break-word; }
  .footer { margin-top: 32px; padding-top: 12px; border-top: 1px solid #1e293b; font-size: 10px; color: #475569; text-align: center; }
</style></head><body>

<h1>${escapeHtml(i.title)}</h1>
<div class="meta">
  ${i.clientName ? `Client: ${escapeHtml(i.clientName)}${i.clientCompany ? ` (${escapeHtml(i.clientCompany)})` : ''} · ` : ''}
  <span class="badge badge-gate">${gateLabel[i.gate] || i.gate}</span>
  <span class="badge badge-lang">${escapeHtml(i.targetLanguage)}</span>
  · Created ${new Date(i.createdAt).toLocaleDateString()}
  ${i.estimatedHours ? ` · Est. ${i.estimatedHours}h` : ''}
  ${i.estimatedCost ? ` · $${Number(i.estimatedCost).toLocaleString()}` : ''}
</div>

<h2>Problem Statement</h2>
<p>${escapeHtml(i.problemStatement)}</p>

<h2>Domain & Stack</h2>
<p><strong>Domain:</strong> ${escapeHtml(i.businessDomain)} · <strong>Language:</strong> ${escapeHtml(i.targetLanguage)} · <strong>Database:</strong> ${escapeHtml(i.targetDatabase)}</p>
${i.budget ? `<p><strong>Budget:</strong> ${escapeHtml(i.budget)}</p>` : ''}
${i.timeline ? `<p><strong>Timeline:</strong> ${escapeHtml(i.timeline)}</p>` : ''}

${(i.targetUsers as string[]).length > 0 ? `<h2>Target Users</h2><ul>${listItems(i.targetUsers)}</ul>` : ''}
${(i.coreWorkflows as string[]).length > 0 ? `<h2>Core Workflows</h2><ul>${listItems(i.coreWorkflows)}</ul>` : ''}
${(i.constraints as string[]).length > 0 ? `<h2>Constraints</h2><ul>${listItems(i.constraints)}</ul>` : ''}
${(i.integrations as string[]).length > 0 ? `<h2>Integrations</h2><ul>${listItems(i.integrations)}</ul>` : ''}

${entities.length > 0 ? `<h2>Entities (${entities.length})</h2>
<table><tr><th>Name</th><th>Fields</th><th>Relationships</th><th>Core</th></tr>
${entities.map((e: any) => `<tr><td><strong>${escapeHtml(e.name)}</strong>${e.description ? `<br/><span style="color:#64748b;font-size:11px">${escapeHtml(e.description)}</span>` : ''}</td><td>${(e.fields || []).map((f: any) => `${escapeHtml(f.name)}: ${escapeHtml(f.type)}`).join(', ')}</td><td>${(e.relationships || []).map((r: any) => `→ ${escapeHtml(r.target)} (${escapeHtml(r.type)})`).join(', ')}</td><td>${e.isCore ? '✓' : ''}</td></tr>`).join('')}
</table>` : ''}

${visuals.length > 0 ? `<h2>Visual Artifacts (${visuals.length})</h2>
${visuals.map((v: any) => `<div class="card"><h3>${escapeHtml(v.title)} <span style="color:#475569">(${v.type} · ${v.status})</span></h3>
${v.description ? `<p style="margin:4px 0;font-size:11px;color:#64748b">${escapeHtml(v.description)}</p>` : ''}
<div class="mermaid-src">${escapeHtml(v.content)}</div></div>`).join('')}` : ''}

${deliverables.length > 0 ? `<h2>Deliverables (${deliverables.length})</h2>
<table><tr><th>Name</th><th>Type</th><th>Status</th><th>Description</th></tr>
${deliverables.map((d: any) => `<tr><td>${escapeHtml(d.name)}</td><td>${d.type}</td><td>${d.status}</td><td>${d.description ? escapeHtml(d.description) : ''}</td></tr>`).join('')}
</table>` : ''}

${criteria.length > 0 ? `<h2>Acceptance Criteria (${criteria.length})</h2>
<table><tr><th>Category</th><th>Priority</th><th>Description</th></tr>
${criteria.map((c: any) => `<tr><td>${escapeHtml(c.category)}</td><td>${escapeHtml(c.priority)}</td><td>${escapeHtml(c.description)}</td></tr>`).join('')}
</table>` : ''}

${i.notes ? `<h2>Notes</h2><p>${escapeHtml(i.notes)}</p>` : ''}

<div class="footer">Generated by The Hearth · Foundry Familiars · ${new Date().toISOString().split('T')[0]}</div>
</body></html>`;
}

export async function GET(
  _req: NextRequest,
  { params }: { params: { id: string } }
) {
  const authResult = await requireDFAuth();
  if (!authResult.authorized) return authResult.response;

  const intake = await prisma.dfIntake.findUnique({
    where: { id: params.id },
    include: {
      entities: true,
      visuals: true,
      deliverables: true,
      acceptanceCriteria: true,
    },
  });

  if (!intake) {
    return NextResponse.json({ error: 'Intake not found' }, { status: 404 });
  }

  const htmlContent = buildIntakeHtml(intake as any);

  // Step 1: Create PDF request
  const createRes = await fetch('https://apps.abacus.ai/api/createConvertHtmlToPdfRequest', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      deployment_token: process.env.ABACUSAI_API_KEY,
      html_content: htmlContent,
      pdf_options: {
        format: 'A4',
        print_background: true,
        margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
      },
    }),
  });

  if (!createRes.ok) {
    return NextResponse.json({ error: 'Failed to initiate PDF generation' }, { status: 500 });
  }

  const { request_id } = await createRes.json();
  if (!request_id) {
    return NextResponse.json({ error: 'No request ID returned' }, { status: 500 });
  }

  // Step 2: Poll for completion
  const maxAttempts = 120;
  let attempts = 0;
  while (attempts < maxAttempts) {
    await new Promise(resolve => setTimeout(resolve, 1500));
    const statusRes = await fetch('https://apps.abacus.ai/api/getConvertHtmlToPdfStatus', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ request_id, deployment_token: process.env.ABACUSAI_API_KEY }),
    });
    const statusResult = await statusRes.json();
    const status = statusResult?.status || 'FAILED';
    if (status === 'SUCCESS' && statusResult?.result?.result) {
      const pdfBuffer = Buffer.from(statusResult.result.result, 'base64');
      const filename = `${intake.title.replace(/[^a-zA-Z0-9_-]/g, '_')}_intake.pdf`;
      return new NextResponse(pdfBuffer, {
        headers: {
          'Content-Type': 'application/pdf',
          'Content-Disposition': `attachment; filename="${filename}"`,
        },
      });
    } else if (status === 'FAILED') {
      return NextResponse.json({ error: 'PDF generation failed' }, { status: 500 });
    }
    attempts++;
  }

  return NextResponse.json({ error: 'PDF generation timed out' }, { status: 500 });
}
