import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { getNodeStatuses } from '@/lib/ai/aiNodeRouter';

/**
 * GET /api/content/pipeline-status
 * Returns live pipeline status for the /admin/content-status dashboard.
 */
export async function GET() {
  try {
    const supabase = await createClient();

    // Fetch node statuses
    const nodeStatuses = await getNodeStatuses();

    // Today's generated articles
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);

    const { data: todayArticles, count: todayCount } = await supabase
      .from('native_articles')
      .select('id, site_id, ai_generated', { count: 'exact' })
      .eq('ai_generated', true)
      .gte('created_at', todayStart.toISOString());

    // Articles by site today
    const siteBreakdown: Record<string, number> = {};
    (todayArticles || []).forEach((a) => {
      const s = a.site_id || 'unknown';
      siteBreakdown[s] = (siteBreakdown[s] || 0) + 1;
    });

    // Press releases remaining (unedited)
    const PRESS_PATTERNS = [/for immediate release/i, /is pleased to announce/i, /announced today/i];
    const { data: publishedArticles } = await supabase
      .from('wp_imported_posts')
      .select('id, content')
      .eq('status', 'published');

    const pressReleasesRemaining = (publishedArticles || []).filter(
      (a) => PRESS_PATTERNS.filter((p) => p.test(a.content || '')).length >= 2
    ).length;

    // Pages with missing content
    const { data: thinImported } = await supabase
      .from('wp_imported_posts')
      .select('id, content')
      .eq('status', 'published');

    const { data: thinNative } = await supabase
      .from('native_articles')
      .select('id, content')
      .eq('status', 'published');

    const allPublished = [...(thinImported || []), ...(thinNative || [])];
    const thinCount = allPublished.filter(
      (a) => (a.content || '').split(/\s+/).filter(Boolean).length < 300
    ).length;

    // SEO meta missing
    const { count: missingSeoImported } = await supabase
      .from('wp_imported_posts')
      .select('id', { count: 'exact' })
      .eq('status', 'published')
      .or('meta_title.is.null,meta_description.is.null');

    const { count: missingSeoNative } = await supabase
      .from('native_articles')
      .select('id', { count: 'exact' })
      .eq('status', 'published')
      .or('meta_title.is.null,meta_description.is.null');

    const missingSeoTotal = (missingSeoImported || 0) + (missingSeoNative || 0);

    return NextResponse.json({
      generatedToday: todayCount || 0,
      siteBreakdown,
      queueDepth: nodeStatuses.reduce((s, n) => s + (n.online ? n.queueDepth : 0), 0),
      pressReleasesRemaining,
      thinContentRemaining: thinCount,
      missingSeoRemaining: missingSeoTotal,
      nodes: nodeStatuses,
      timestamp: new Date().toISOString(),
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
