import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';

// ─── Health log endpoint — called fire-and-forget from hybridRouter ───────────
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { provider, success, latencyMs, model, priority, errorMessage, isFailover } = body;

    const supabase = await createClient();
    await supabase.from('ai_health_log').insert({
      provider,
      success,
      latency_ms: latencyMs,
      model_used: model,
      priority,
      error_message: errorMessage || null,
      is_failover: isFailover || false,
      logged_at: new Date().toISOString(),
    });

    return NextResponse.json({ ok: true });
  } catch {
    // Silently ignore — health logging must never break the main flow
    return NextResponse.json({ ok: true });
  }
}

// ─── GET — 24hr stats for health dashboard ────────────────────────────────────
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const { data: profile } = await supabase.from('user_profiles').select('role').eq('id', user.id).single();
    if (!['administrator', 'admin'].includes(profile?.role || '')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();

    const { data: logs } = await supabase
      .from('ai_health_log')
      .select('*')
      .gte('logged_at', since)
      .order('logged_at', { ascending: true });

    const allLogs = logs || [];

    // Aggregate stats
    const totalRequests = allLogs.length;
    const localServed = allLogs.filter(l => l.provider === 'ollama' && l.success).length;
    const cloudServed = allLogs.filter(l => l.provider === 'anthropic' && l.success).length;
    const failoverEvents = allLogs.filter(l => l.is_failover).length;
    const errors = allLogs.filter(l => !l.success);
    const avgLatency = allLogs.length > 0
      ? Math.round(allLogs.reduce((sum, l) => sum + (l.latency_ms || 0), 0) / allLogs.length)
      : 0;

    // Check if local has been down > 30 minutes
    const ollamaLogs = allLogs.filter(l => l.provider === 'ollama');
    const lastOllamaSuccess = ollamaLogs.filter(l => l.success).slice(-1)[0];
    const lastOllamaAttempt = ollamaLogs.slice(-1)[0];
    const ollamaDownMinutes = lastOllamaAttempt && !lastOllamaAttempt.success && lastOllamaSuccess
      ? Math.floor((Date.now() - new Date(lastOllamaAttempt.logged_at).getTime()) / 60000)
      : 0;

    // Build hourly timeline (24 buckets)
    const timeline: Array<{ hour: string; local: number; cloud: number }> = [];
    for (let i = 23; i >= 0; i--) {
      const hourStart = new Date(Date.now() - i * 60 * 60 * 1000);
      const hourEnd = new Date(Date.now() - (i - 1) * 60 * 60 * 1000);
      const hourLogs = allLogs.filter(l => {
        const t = new Date(l.logged_at).getTime();
        return t >= hourStart.getTime() && t < hourEnd.getTime();
      });
      timeline.push({
        hour: hourStart.toISOString(),
        local: hourLogs.filter(l => l.provider === 'ollama' && l.success).length,
        cloud: hourLogs.filter(l => l.provider === 'anthropic' && l.success).length,
      });
    }

    return NextResponse.json({
      stats: { totalRequests, localServed, cloudServed, failoverEvents, avgLatency },
      errors: errors.slice(-20),
      timeline,
      ollamaDownMinutes,
      lastOllamaSuccess: lastOllamaSuccess?.logged_at || null,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
