import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { spanAnnotations, charts } from '@/lib/db/schema';
import { eq, desc } from 'drizzle-orm';

function sanitizeCsvCell(value: string): string {
  if (/^[=+@\-]/.test(value)) {
    return `'${value}`;
  }
  return value;
}

/**
 * GET /api/span-annotations/export
 * 
 * Export span annotations in ML pipeline format (JSON).
 * 
 * @deprecated The ML service now queries annotations directly from PostgreSQL.
 * This endpoint is retained for data backup and external analysis purposes only.
 * 
 * Query params:
 * - chartId: (optional) specific chart ID. If omitted, uses most recent chart.
 * - format: (optional) 'json' (default) or 'csv'
 * 
 * ML Pipeline JSON format:
 * {
 *   "annotations": [
 *     {
 *       "id": 1,
 *       "start_time": "2024-01-01T00:00:00Z",
 *       "end_time": "2024-01-01T01:00:00Z",
 *       "label": "bull_flag",
 *       "confidence": 4,
 *       "notes": "Clear pattern"
 *     }
 *   ]
 * }
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = request.nextUrl;
    let chartId = searchParams.get('chartId');
    const format = searchParams.get('format') || 'json';

    // Fall back to most recent chart if no chartId provided
    if (!chartId) {
      const latest = await db
        .select({ id: charts.id })
        .from(charts)
        .orderBy(desc(charts.created_at))
        .limit(1);
      
      if (latest.length === 0) {
        // No charts found - return empty export
        if (format === 'json') {
          return NextResponse.json({ annotations: [] });
        } else {
          return new NextResponse('id,start_time,end_time,label,confidence,outcome,notes\n', {
            headers: {
              'Content-Type': 'text/csv',
              'Content-Disposition': 'attachment; filename="span_annotations.csv"',
            },
          });
        }
      }
      chartId = String(latest[0].id);
    }

    const chartIdNum = parseInt(chartId, 10);
    
    // Fetch all span annotations for the chart
    const spans = await db
      .select()
      .from(spanAnnotations)
      .where(eq(spanAnnotations.chart_id, chartIdNum))
      .orderBy(spanAnnotations.start_time);

    if (format === 'json') {
      // Convert to ML pipeline format
      const annotations = spans.map(span => ({
        id: span.id,
        start_time: span.start_time,
        end_time: span.end_time,
        label: span.label,
        confidence: span.confidence,
        outcome: span.outcome,
        notes: span.notes,
        sub_spans: span.sub_spans,
        color: span.color,
        source: span.source,
        model_prediction: span.model_prediction,
        created_at: span.created_at,
      }));

      return NextResponse.json({ 
        annotations,
        chart_id: chartIdNum,
        export_timestamp: new Date().toISOString(),
        total_count: annotations.length,
      });
    } else if (format === 'csv') {
      // CSV export
      const csvRows = ['id,start_time,end_time,label,confidence,outcome,notes'];
      
      for (const span of spans) {
        const notes = span.notes ? `"${span.notes.replace(/"/g, '""')}"` : '';

        csvRows.push(
          `${span.id},${sanitizeCsvCell(String(span.start_time))},${sanitizeCsvCell(String(span.end_time))},${sanitizeCsvCell(span.label)},${span.confidence || ''},${span.outcome ? sanitizeCsvCell(span.outcome) : ''},${notes}`
        );
      }

      const csvContent = csvRows.join('\n');

      return new NextResponse(csvContent, {
        headers: {
          'Content-Type': 'text/csv',
          'Content-Disposition': 'attachment; filename="span_annotations.csv"',
        },
      });
    } else {
      return NextResponse.json(
        { error: 'Invalid format parameter. Use "json" or "csv".' },
        { status: 400 }
      );
    }
  } catch (error: any) {
    console.error('Error exporting span annotations:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
