import { NextRequest, NextResponse } from 'next/server'

/**
 * Agent Statistics API
 *
 * GET - Get aggregated statistics for all agents
 */

interface AgentMetric {
  agentType: string
  name: string
  color: string
  sessions: number
  messagesProcessed: number
  avgResponseTime: number
  errorRate: number
  successRate: number
  trend: 'up' | 'down' | 'stable'
  trendValue: number
}

interface DailyStats {
  date: string
  sessions: number
  messages: number
  errors: number
  avgLatency: number
}

interface HourlyLatency {
  timestamp: string
  value: number
}

// Mock agent metrics
function getAgentMetrics(): AgentMetric[] {
  return [
    {
      agentType: 'tutor-agent',
      name: 'TutorAgent',
      color: '#3b82f6',
      sessions: 156,
      messagesProcessed: 4521,
      avgResponseTime: 234,
      errorRate: 0.3,
      successRate: 99.7,
      trend: 'up',
      trendValue: 12
    },
    {
      agentType: 'grader-agent',
      name: 'GraderAgent',
      color: '#10b981',
      sessions: 45,
      messagesProcessed: 1205,
      avgResponseTime: 1102,
      errorRate: 0.5,
      successRate: 99.5,
      trend: 'stable',
      trendValue: 2
    },
    {
      agentType: 'quality-judge',
      name: 'QualityJudge',
      color: '#f59e0b',
      sessions: 89,
      messagesProcessed: 8934,
      avgResponseTime: 89,
      errorRate: 0.1,
      successRate: 99.9,
      trend: 'up',
      trendValue: 8
    },
    {
      agentType: 'alert-agent',
      name: 'AlertAgent',
      color: '#ef4444',
      sessions: 12,
      messagesProcessed: 892,
      avgResponseTime: 45,
      errorRate: 0.0,
      successRate: 100,
      trend: 'stable',
      trendValue: 0
    },
    {
      agentType: 'orchestrator',
      name: 'Orchestrator',
      color: '#8b5cf6',
      sessions: 234,
      messagesProcessed: 15420,
      avgResponseTime: 12,
      errorRate: 0.2,
      successRate: 99.8,
      trend: 'up',
      trendValue: 15
    }
  ]
}

// Generate mock daily stats for the last N days
function getDailyStats(days: number): DailyStats[] {
  const stats: DailyStats[] = []
  const now = new Date()

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)

    stats.push({
      date: date.toISOString().split('T')[0],
      sessions: 400 + Math.floor(Math.random() * 150),
      messages: 11000 + Math.floor(Math.random() * 5000),
      errors: 8 + Math.floor(Math.random() * 12),
      avgLatency: 140 + Math.floor(Math.random() * 25)
    })
  }

  return stats
}

// Generate hourly latency data for the last 24 hours
function getHourlyLatency(): HourlyLatency[] {
  const data: HourlyLatency[] = []

  for (let i = 0; i < 24; i++) {
    data.push({
      timestamp: `${i.toString().padStart(2, '0')}:00`,
      value: 100 + Math.floor(Math.random() * 100)
    })
  }

  return data
}

// GET - Get statistics
export async function GET(request: NextRequest) {
  try {
    const url = new URL(request.url)
    const timeRange = url.searchParams.get('range') || '7d'

    // Determine days based on time range
    const days = timeRange === '24h' ? 1 : timeRange === '7d' ? 7 : 30

    const agentMetrics = getAgentMetrics()
    const dailyStats = getDailyStats(days)
    const hourlyLatency = getHourlyLatency()

    // Calculate totals
    const totals = {
      sessions: agentMetrics.reduce((sum, m) => sum + m.sessions, 0),
      messages: agentMetrics.reduce((sum, m) => sum + m.messagesProcessed, 0),
      avgLatency: Math.round(
        agentMetrics.reduce((sum, m) => sum + m.avgResponseTime, 0) / agentMetrics.length
      ),
      avgErrorRate: parseFloat(
        (agentMetrics.reduce((sum, m) => sum + m.errorRate, 0) / agentMetrics.length).toFixed(2)
      )
    }

    // Calculate week totals from daily stats
    const weekTotals = {
      sessions: dailyStats.reduce((sum, d) => sum + d.sessions, 0),
      messages: dailyStats.reduce((sum, d) => sum + d.messages, 0),
      errors: dailyStats.reduce((sum, d) => sum + d.errors, 0),
      avgLatency: Math.round(
        dailyStats.reduce((sum, d) => sum + d.avgLatency, 0) / dailyStats.length
      )
    }

    // Calculate trends
    const trends = {
      sessions: {
        value: 12,
        direction: 'up' as const
      },
      messages: {
        value: 8,
        direction: 'up' as const
      },
      latency: {
        value: 5,
        direction: 'down' as const // down is good for latency
      },
      errors: {
        value: 3,
        direction: 'up' as const
      }
    }

    return NextResponse.json({
      agentMetrics,
      dailyStats,
      hourlyLatency,
      totals,
      weekTotals,
      trends,
      timeRange,
      timestamp: new Date().toISOString()
    })
  } catch (error) {
    console.error('Error fetching statistics:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch statistics' },
      { status: 500 }
    )
  }
}
