// Weekly $${VOCAB.brief} Generator
// Generates and sends executive summary emails

import prisma from '@/lib/db';
import { logSimpleAction } from './agent-logger';
import { getDunningStats } from './dunning';
import { getReconciliationStats } from './reconciliation';
import { getInventoryStats } from './inventory-triggers';
import { getAPStats } from './ap-automation';
import { getExpenseStats } from './expense-categorizer';
import { BRAND, VOCAB } from '@/lib/white-label/constants';

export interface BriefSection {
  title: string;
  icon: string;
  items: { label: string; value: string | number; trend?: 'up' | 'down' | 'neutral'; alert?: boolean }[];
}

export interface FamiliarBrief {
  generatedAt: Date;
  periodStart: Date;
  periodEnd: Date;
  executiveSummary: string;
  sections: BriefSection[];
  alerts: string[];
  recommendations: string[];
}

// Generate the weekly brief
export async function generateFamiliarBrief(): Promise<FamiliarBrief> {
  const now = new Date();
  const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  
  // Gather all stats
  const [dunningStats, reconStats, inventoryStats, apStats, expenseStats] = await Promise.all([
    getDunningStats(),
    getReconciliationStats(),
    getInventoryStats(),
    getAPStats(),
    getExpenseStats(),
  ]);
  
  // Get recent agent actions
  const recentActions = await prisma.agentAction.count({
    where: { createdAt: { gte: weekAgo } },
  });
  
  const anomaliesDetected = await prisma.agentAction.count({
    where: { createdAt: { gte: weekAgo }, anomalyDetected: true },
  });
  
  // Get order metrics
  const ordersThisWeek = await prisma.swagOrder.count({
    where: { createdAt: { gte: weekAgo } },
  });
  
  const orderRevenue = await prisma.swagOrder.aggregate({
    where: { createdAt: { gte: weekAgo }, status: 'paid' },
    _sum: { total: true },
  });
  
  // Build sections
  const sections: BriefSection[] = [
    {
      title: 'Order-to-Cash Health',
      icon: '💰',
      items: [
        { label: 'Orders This Week', value: ordersThisWeek },
        { label: 'Revenue', value: `$${(orderRevenue._sum.total || 0).toFixed(2)}` },
        { label: 'AR Overdue', value: dunningStats.totalOverdue, alert: dunningStats.totalOverdue > 0 },
        { label: 'Overdue Amount', value: `$${dunningStats.totalOverdueAmount.toFixed(2)}`, alert: dunningStats.totalOverdueAmount > 1000 },
        { label: 'Reconciliation Discrepancies', value: reconStats.discrepancies, alert: reconStats.discrepancies > 0 },
      ],
    },
    {
      title: 'Inventory & Procurement',
      icon: '📦',
      items: [
        { label: 'Products Tracked', value: inventoryStats.totalProducts },
        { label: 'Low Stock Alerts', value: inventoryStats.lowStock, alert: inventoryStats.lowStock > 0 },
        { label: 'Out of Stock', value: inventoryStats.outOfStock, alert: inventoryStats.outOfStock > 0 },
        { label: 'Pending Reorders', value: inventoryStats.orderedAlerts },
        { label: 'Stock Movements (7d)', value: inventoryStats.recentMovements },
      ],
    },
    {
      title: 'Accounts Payable',
      icon: '📝',
      items: [
        { label: 'Pending Approval', value: apStats.pendingApproval, alert: apStats.pendingApproval > 5 },
        { label: 'Pending Amount', value: `$${apStats.pendingAmount.toFixed(2)}` },
        { label: 'Scheduled Payments', value: apStats.scheduledPayments },
        { label: 'Overdue Invoices', value: apStats.overdueCount, alert: apStats.overdueCount > 0 },
        { label: 'Paid This Month', value: `$${apStats.paidAmountThisMonth.toFixed(2)}` },
      ],
    },
    {
      title: 'Expense Intelligence',
      icon: '🧠',
      items: [
        { label: 'Total Expenses', value: expenseStats.totalExpenses },
        { label: 'Auto-Categorized', value: expenseStats.categorized },
        { label: 'Needs Review', value: expenseStats.uncategorized, alert: expenseStats.uncategorized > 10 },
        { label: 'Flagged for Review', value: expenseStats.flagged, alert: expenseStats.flagged > 0 },
        { label: 'Avg AI Confidence', value: `${(expenseStats.avgConfidence * 100).toFixed(0)}%` },
      ],
    },
    {
      title: 'Agent Activity',
      icon: '🤖',
      items: [
        { label: 'Actions This Week', value: recentActions },
        { label: 'Anomalies Detected', value: anomaliesDetected, alert: anomaliesDetected > 5 },
        { label: 'Automation Rate', value: recentActions > 0 ? `${((recentActions - anomaliesDetected) / recentActions * 100).toFixed(0)}%` : 'N/A' },
      ],
    },
  ];
  
  // Generate alerts
  const alerts: string[] = [];
  if (dunningStats.totalOverdue > 0) {
    alerts.push(`⚠️ ${dunningStats.totalOverdue} invoices overdue totaling $${dunningStats.totalOverdueAmount.toFixed(2)}`);
  }
  if (reconStats.discrepancies > 0) {
    alerts.push(`🚨 ${reconStats.discrepancies} reconciliation discrepancies need review`);
  }
  if (inventoryStats.outOfStock > 0) {
    alerts.push(`📦 ${inventoryStats.outOfStock} products out of stock`);
  }
  if (apStats.overdueCount > 0) {
    alerts.push(`📝 ${apStats.overdueCount} vendor invoices are overdue`);
  }
  if (expenseStats.flagged > 0) {
    alerts.push(`🚩 ${expenseStats.flagged} expenses flagged for manual review`);
  }
  
  // Generate recommendations
  const recommendations: string[] = [];
  if (dunningStats.avgDaysOverdue > 20) {
    recommendations.push('Consider tightening payment terms or offering early payment discounts');
  }
  if (inventoryStats.lowStock > 3) {
    recommendations.push('Review reorder thresholds – multiple products approaching stockout');
  }
  if (expenseStats.avgConfidence < 0.7) {
    recommendations.push('Train expense categorization model with more examples for better accuracy');
  }
  if (recentActions > 100 && anomaliesDetected > 10) {
    recommendations.push('High anomaly rate detected – review sniff-check thresholds');
  }
  
  // Executive summary
  const executiveSummary = `This week, your Familiars processed ${ordersThisWeek} orders generating $${(orderRevenue._sum.total || 0).toFixed(2)} in revenue. ` +
    `${recentActions} autonomous actions were executed with ${anomaliesDetected} anomalies detected. ` +
    (alerts.length > 0 ? `There are ${alerts.length} items requiring attention.` : 'All systems operating normally.');
  
  return {
    generatedAt: now,
    periodStart: weekAgo,
    periodEnd: now,
    executiveSummary,
    sections,
    alerts,
    recommendations,
  };
}

// Generate HTML email content
export function generateBriefHTML(brief: FamiliarBrief): string {
  const formatDate = (d: Date) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  
  const sectionsHTML = brief.sections.map(section => `
    <div style="background: rgba(255,255,255,0.05); border-radius: 12px; padding: 20px; margin-bottom: 20px;">
      <h3 style="color: #0EA5E9; margin: 0 0 15px 0; font-size: 18px;">${section.icon} ${section.title}</h3>
      <table style="width: 100%; border-collapse: collapse;">
        ${section.items.map(item => `
          <tr>
            <td style="padding: 8px 0; color: #94a3b8; border-bottom: 1px solid rgba(255,255,255,0.1);">${item.label}</td>
            <td style="padding: 8px 0; text-align: right; font-weight: 600; border-bottom: 1px solid rgba(255,255,255,0.1); color: ${item.alert ? '#ef4444' : '#e2e8f0'};">
              ${item.alert ? '⚠️ ' : ''}${item.value}
            </td>
          </tr>
        `).join('')}
      </table>
    </div>
  `).join('');
  
  const alertsHTML = brief.alerts.length > 0 ? `
    <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid #ef4444; border-radius: 12px; padding: 20px; margin-bottom: 20px;">
      <h3 style="color: #ef4444; margin: 0 0 15px 0;">🚨 Alerts Requiring Attention</h3>
      <ul style="margin: 0; padding-left: 20px; color: #fecaca;">
        ${brief.alerts.map(a => `<li style="margin-bottom: 8px;">${a}</li>`).join('')}
      </ul>
    </div>
  ` : '';
  
  const recommendationsHTML = brief.recommendations.length > 0 ? `
    <div style="background: rgba(6, 182, 212, 0.1); border: 1px solid #0EA5E9; border-radius: 12px; padding: 20px; margin-bottom: 20px;">
      <h3 style="color: #0EA5E9; margin: 0 0 15px 0;">💡 Recommendations</h3>
      <ul style="margin: 0; padding-left: 20px; color: #a5f3fc;">
        ${brief.recommendations.map(r => `<li style="margin-bottom: 8px;">${r}</li>`).join('')}
      </ul>
    </div>
  ` : '';
  
  return `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>${VOCAB.brief}</title>
    </head>
    <body style="font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; background: linear-gradient(135deg, #0C1222 0%, #1a1f3a 100%); color: #e2e8f0; margin: 0; padding: 40px;">
      <div style="max-width: 700px; margin: 0 auto;">
        <div style="text-align: center; margin-bottom: 30px;">
          <h1 style="color: #0EA5E9; margin: 0; font-size: 28px;">👻 ${BRAND.companyName}</h1>
          <p style="color: #64748b; margin: 10px 0 0 0;">Weekly Intelligence Brief</p>
          <p style="color: #475569; font-size: 14px; margin: 5px 0 0 0;">${formatDate(brief.periodStart)} – ${formatDate(brief.periodEnd)}</p>
        </div>
        
        <div style="background: rgba(255,255,255,0.05); border-radius: 12px; padding: 20px; margin-bottom: 20px;">
          <h3 style="color: #f1f5f9; margin: 0 0 10px 0;">📊 Executive Summary</h3>
          <p style="color: #cbd5e1; line-height: 1.6; margin: 0;">${brief.executiveSummary}</p>
        </div>
        
        ${alertsHTML}
        ${sectionsHTML}
        ${recommendationsHTML}
        
        <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.1);">
          <p style="color: #64748b; font-size: 12px; margin: 0;">Generated automatically by your Familiars</p>
          <p style="color: #475569; font-size: 12px; margin: 5px 0 0 0;">
            <a href="https://${BRAND.domain}/ghost-control/order-to-cash" style="color: #0EA5E9;">View Full Dashboard</a>
          </p>
        </div>
      </div>
    </body>
    </html>
  `;
}

// Send the weekly brief
export async function sendWeeklyBrief(recipientEmail?: string): Promise<boolean> {
  try {
    const brief = await generateFamiliarBrief();
    const htmlContent = generateBriefHTML(brief);
    
    const email = recipientEmail || process.env.ADMIN_EMAIL || 'ghostfoundrysyndicate@outlook.com';
    
    const response = await fetch('https://apps.abacus.ai/api/sendNotificationEmail', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        api_key: process.env.ABACUSAI_API_KEY,
        app_id: process.env.WEB_APP_ID,
        notification_id: process.env.NOTIF_ID_WEEKLY_SYNDICATE_BRIEF || process.env.NOTIF_ID_RECONCILIATION_ALERT,
        recipient_email: email,
        subject: `👻 $${VOCAB.brief}: ${new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`,
        body_html: htmlContent,
      }),
    });
    
    if (response.ok) {
      await logSimpleAction({
        actionType: 'send_confirmation',
        targetEntity: 'FamiliarBrief',
        targetId: `brief-${Date.now()}`,
        input: { recipient: email },
        output: { sent: true, alertCount: brief.alerts.length },
        confidence: 1.0,
        anomalyDetected: false,
      });
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('[FamiliarBrief] Failed to send:', error);
    return false;
  }
}
