export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const STRIPE_API_VERSION = '2024-12-18.acacia';
const ABACUS_API_KEY = process.env.ABACUSAI_API_KEY;

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { sessionId, title, clientName, clientEmail, clientCompany, businessDomain,
      problemStatement, budget, timeline, notes, targetUsers, coreWorkflows, constraints, integrations } = body;

    if (!title || !businessDomain || !problemStatement || !clientEmail) {
      return NextResponse.json({ error: 'Required fields missing.' }, { status: 400 });
    }

    // Re-verify payment
    if (sessionId && STRIPE_SECRET_KEY) {
      const res = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, {
        headers: {
          'Authorization': `Bearer ${STRIPE_SECRET_KEY}`,
          'Stripe-Version': STRIPE_API_VERSION,
        },
      });
      const session = await res.json();
      if (session.payment_status !== 'paid' || session.metadata?.service !== 'ai-scope') {
        return NextResponse.json({ error: 'Payment not verified.' }, { status: 403 });
      }
    }

    // Create intake in the database
    const intake = await prisma.dfIntake.create({
      data: {
        title,
        clientName: clientName || null,
        clientCompany: clientCompany || null,
        businessDomain,
        problemStatement,
        targetUsers: targetUsers || [],
        coreWorkflows: coreWorkflows || [],
        constraints: constraints || [],
        integrations: integrations || [],
        targetLanguage: 'typescript-react',
        targetDatabase: 'postgresql',
        budget: budget || null,
        timeline: timeline || null,
        notes: notes ? `[AI Scope Service - $197] ${notes}` : '[AI Scope Service - $197]',
        gate: 'intake_draft',
        createdBy: `ai-scope:${clientEmail}`,
      },
    });

    // Use LLM to generate enhanced scope analysis
    let llmAnalysis = '';
    if (ABACUS_API_KEY) {
      try {
        const llmRes = await fetch('https://apps.abacus.ai/api/v1/chat/completions', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${ABACUS_API_KEY}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            messages: [{
              role: 'user',
              content: `You are a senior software architect. Analyze this project and provide a comprehensive scope assessment.

Project: ${title}
Domain: ${businessDomain}
Problem: ${problemStatement}
Target Users: ${(targetUsers || []).join(', ')}
Core Workflows: ${(coreWorkflows || []).join(', ')}
Constraints: ${(constraints || []).join(', ')}
Integrations: ${(integrations || []).join(', ')}
Budget: ${budget || 'Not specified'}
Timeline: ${timeline || 'Not specified'}

Provide your analysis in these sections:
1. EXECUTIVE SUMMARY (2-3 sentences)
2. RECOMMENDED DATA ENTITIES (list each with key fields)
3. ARCHITECTURE RECOMMENDATION (tech stack, patterns)
4. KEY WORKFLOWS (describe 3-5 main user flows)
5. RISK ASSESSMENT (top 3 risks and mitigations)
6. COMPLEXITY SCORE (1-10 with justification)
7. TIME ESTIMATE (in developer-weeks)
8. COST ESTIMATE (USD range based on market rates)
9. RECOMMENDED NEXT STEPS (3-5 actionable items)

Be specific, technical, and actionable. This will be delivered as a professional scope document.`
            }],
            model: 'claude-3-5-sonnet-20241022',
            temperature: 0.3,
            max_tokens: 4000,
          }),
        });
        const llmData = await llmRes.json();
        llmAnalysis = llmData.choices?.[0]?.message?.content || '';
      } catch (llmErr) {
        console.error('LLM analysis error:', llmErr);
        llmAnalysis = 'AI analysis unavailable — manual scope will be provided.';
      }
    }

    // Generate PDF
    const pdfHtml = buildScopePdfHtml({
      title, clientName, clientCompany, clientEmail, businessDomain,
      problemStatement, targetUsers, coreWorkflows, constraints,
      integrations, budget, timeline, notes, llmAnalysis,
    });

    let pdfUrl = '';
    if (ABACUS_API_KEY) {
      try {
        const createRes = await fetch('https://apps.abacus.ai/api/createConvertHtmlToPdfRequest', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            deployment_token: ABACUS_API_KEY,
            html_content: pdfHtml,
            pdf_options: {
              format: 'A4',
              print_background: true,
              margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
            },
          }),
        });
        const { request_id } = await createRes.json();

        if (request_id) {
          // Poll for completion
          let attempts = 0;
          while (attempts < 60) {
            await new Promise(r => setTimeout(r, 2000));
            const statusRes = await fetch('https://apps.abacus.ai/api/getConvertHtmlToPdfStatus', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ request_id, deployment_token: ABACUS_API_KEY }),
            });
            const statusResult = await statusRes.json();
            if (statusResult?.status === 'SUCCESS' && statusResult?.result?.result) {
              // Send PDF via email
              await sendScopeEmail(clientEmail, clientName || 'there', title, statusResult.result.result);
              pdfUrl = 'sent';
              break;
            } else if (statusResult?.status === 'FAILED') {
              console.error('PDF generation failed');
              break;
            }
            attempts++;
          }
        }
      } catch (pdfErr) {
        console.error('PDF generation error:', pdfErr);
      }
    }

    // Update intake with analysis
    await prisma.dfIntake.update({
      where: { id: intake.id },
      data: {
        notes: `[AI Scope Service - $197]\n\nStripe Session: ${sessionId}\nEmail: ${clientEmail}\nPDF: ${pdfUrl === 'sent' ? 'Delivered' : 'Pending'}\n\n--- AI Analysis ---\n${llmAnalysis}`,
        gate: 'intake_approved',
        intakeApprovedAt: new Date(),
        intakeApprovedBy: 'ai-scope-service',
      },
    });

    return NextResponse.json({ success: true, intakeId: intake.id });
  } catch (error) {
    console.error('AI Scope submit error:', error);
    return NextResponse.json({ error: 'Failed to process scope request.' }, { status: 500 });
  }
}

async function sendScopeEmail(email: string, name: string, projectTitle: string, pdfBase64: string) {
  const NOTIF_API_KEY = process.env.ABACUSAI_API_KEY;
  const WEB_APP_ID = process.env.WEB_APP_ID;

  if (!NOTIF_API_KEY || !WEB_APP_ID) return;

  try {
    await fetch('https://apps.abacus.ai/api/sendNotificationEmail', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        deployment_token: NOTIF_API_KEY,
        web_app_id: WEB_APP_ID,
        recipient_email: email,
        subject: `Your AI Project Scope: ${projectTitle}`,
        body_html: `
          <div style="font-family: 'Segoe UI', sans-serif; max-width: 600px; margin: 0 auto; background: #0f172a; color: #e2e8f0; padding: 40px; border-radius: 12px;">
            <h1 style="color: #fff; margin-bottom: 8px;">Your Project Scope is Ready</h1>
            <p style="color: #94a3b8;">Hi ${escapeHtml(name)},</p>
            <p style="color: #cbd5e1;">Your AI-powered scope document for <strong style="color: #fff;">${escapeHtml(projectTitle)}</strong> has been generated by The Hearth.</p>
            <p style="color: #cbd5e1;">The branded PDF is attached to this email. It includes:</p>
            <ul style="color: #cbd5e1;">
              <li>Executive summary and architecture recommendations</li>
              <li>Data entity definitions and relationships</li>
              <li>Key workflow analysis</li>
              <li>Risk assessment and complexity scoring</li>
              <li>Time and cost estimates</li>
              <li>Recommended next steps</li>
            </ul>
            <p style="color: #94a3b8; font-size: 12px; margin-top: 24px;">— Tesa Aria, AI Operations Lead<br/>Foundry Familiars<br/>spookysoftwaresyndicate.com</p>
          </div>
        `,
        attachments: [{
          filename: `${projectTitle.replace(/[^a-zA-Z0-9_-]/g, '_')}_AI_Scope.pdf`,
          content: pdfBase64,
          content_type: 'application/pdf',
        }],
      }),
    });
  } catch (emailErr) {
    console.error('Email send error:', emailErr);
  }
}

function buildScopePdfHtml(data: {
  title: string; clientName: string; clientCompany: string; clientEmail: string;
  businessDomain: string; problemStatement: string; targetUsers: string[];
  coreWorkflows: string[]; constraints: string[]; integrations: string[];
  budget: string; timeline: string; notes: string; llmAnalysis: string;
}): string {
  const d = data;
  const listHtml = (arr: string[]) => arr.filter(Boolean).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: 28px; color: #fff; margin-bottom: 4px; }
  h2 { font-size: 18px; color: #3b82f6; margin: 28px 0 10px; border-bottom: 1px solid #1e293b; padding-bottom: 6px; }
  h3 { font-size: 14px; color: #94a3b8; margin: 14px 0 6px; }
  .meta { font-size: 12px; color: #64748b; margin-bottom: 24px; }
  .badge { display: inline-block; padding: 3px 10px; border-radius: 4px; font-size: 11px; font-weight: 600; background: #1e40af; color: #93c5fd; margin-right: 6px; }
  p, li { font-size: 13px; line-height: 1.7; color: #cbd5e1; }
  ul { padding-left: 20px; margin: 6px 0; }
  .card { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 16px; margin: 10px 0; }
  .analysis { background: #0f172a; border: 1px solid #334155; border-radius: 6px; padding: 16px; font-size: 13px; line-height: 1.7; white-space: pre-wrap; color: #e2e8f0; }
  .footer { margin-top: 40px; padding-top: 16px; border-top: 1px solid #1e293b; font-size: 10px; color: #475569; text-align: center; }
  .header-badge { background: #065f46; color: #6ee7b7; }
  table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 12px; }
  th { background: #1e293b; color: #94a3b8; text-align: left; padding: 8px; font-weight: 600; }
  td { padding: 8px; border-bottom: 1px solid #1e293b; color: #cbd5e1; }
</style></head><body>

<h1>${escapeHtml(d.title)}</h1>
<div class="meta">
  <span class="badge">AI Project Scope</span>
  <span class="badge header-badge">$197 Service</span>
  ${d.clientName ? `· Prepared for: ${escapeHtml(d.clientName)}` : ''}
  ${d.clientCompany ? ` (${escapeHtml(d.clientCompany)})` : ''}
  · ${new Date().toLocaleDateString()}
</div>

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

<h2>Project Parameters</h2>
<table>
  <tr><th>Domain</th><td>${escapeHtml(d.businessDomain)}</td></tr>
  ${d.budget ? `<tr><th>Budget</th><td>${escapeHtml(d.budget)}</td></tr>` : ''}
  ${d.timeline ? `<tr><th>Timeline</th><td>${escapeHtml(d.timeline)}</td></tr>` : ''}
</table>

${d.targetUsers.filter(Boolean).length > 0 ? `<h2>Target Users</h2><ul>${listHtml(d.targetUsers)}</ul>` : ''}
${d.coreWorkflows.filter(Boolean).length > 0 ? `<h2>Core Workflows</h2><ul>${listHtml(d.coreWorkflows)}</ul>` : ''}
${d.constraints.filter(Boolean).length > 0 ? `<h2>Constraints</h2><ul>${listHtml(d.constraints)}</ul>` : ''}
${d.integrations.filter(Boolean).length > 0 ? `<h2>Integrations</h2><ul>${listHtml(d.integrations)}</ul>` : ''}

<h2>AI-Powered Scope Analysis</h2>
<div class="analysis">${escapeHtml(d.llmAnalysis)}</div>

<div class="footer">
  Generated by The Hearth · Foundry Familiars · spookysoftwaresyndicate.com<br/>
  AI Project Scoping Service · ${new Date().toISOString().split('T')[0]}
</div>

</body></html>`;
}
