export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { getSniffCheckStats } from '@/lib/order-to-cash/sniff-check';
import { getProposalStats } from '@/lib/order-to-cash/self-mod';

export async function GET() {
  try {
    // Get recent executions
    const recentExecutions = await prisma.orderToCashExecution.findMany({
      orderBy: { createdAt: 'desc' },
      take: 10,
    });

    // Get execution stats
    const [activeCount, completedCount, pausedCount, failedCount] = await Promise.all([
      prisma.orderToCashExecution.count({ where: { status: 'active' } }),
      prisma.orderToCashExecution.count({ where: { status: 'completed' } }),
      prisma.orderToCashExecution.count({ where: { status: 'paused' } }),
      prisma.orderToCashExecution.count({ where: { status: 'failed' } }),
    ]);

    // Get recent agent actions
    const recentActions = await prisma.agentAction.findMany({
      orderBy: { createdAt: 'desc' },
      take: 20,
    });

    // Get anomaly counts
    const anomalyCount = await prisma.agentAction.count({
      where: { anomalyDetected: true },
    });

    // Get sniff-check stats
    const sniffCheckStats = await getSniffCheckStats();

    // Get self-mod stats
    const selfModStats = await getProposalStats();

    // Get pattern count
    const patternCount = await prisma.detectedPattern.count();
    const significantPatternCount = await prisma.detectedPattern.count({
      where: {
        confidence: { gte: 0.8 },
        appliedToSystem: false,
      },
    });

    // Get AR stats
    const arStats = await prisma.accountsReceivable.groupBy({
      by: ['status'],
      _count: true,
      _sum: { amountDue: true },
    });

    // Calculate autonomous rate
    const totalExecutions = completedCount + pausedCount + failedCount;
    const humanInterventions = await prisma.orderToCashExecution.aggregate({
      _sum: { humanInterventions: true },
    });
    const autonomousRate = totalExecutions > 0
      ? ((totalExecutions - (humanInterventions._sum.humanInterventions || 0)) / totalExecutions) * 100
      : 100;

    return NextResponse.json({
      executions: {
        active: activeCount,
        completed: completedCount,
        paused: pausedCount,
        failed: failedCount,
        recent: recentExecutions,
      },
      actions: {
        recent: recentActions,
        anomalyCount,
      },
      sniffChecks: sniffCheckStats,
      selfMod: selfModStats,
      patterns: {
        total: patternCount,
        significant: significantPatternCount,
      },
      ar: arStats,
      metrics: {
        autonomousRate: Math.round(autonomousRate),
        totalExecutions,
      },
    });
  } catch (error) {
    console.error('Error fetching dashboard data:', error);
    return NextResponse.json({ error: 'Failed to fetch dashboard data' }, { status: 500 });
  }
}
