import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

// Request validation schema
const aiLawyerRequestSchema = z.object({
  message: z.string().min(1, 'Message cannot be empty').max(5000, 'Message too long'),
  conversationId: z.string().optional(),
  history: z.array(z.object({
    role: z.enum(['user', 'assistant']),
    content: z.string()
  })).optional(),
  useRag: z.boolean().optional().default(true)
});

// AI Lawyer RAG Service configuration
const AI_LAWYER_RAG_URL = process.env.AI_LAWYER_RAG_URL || 'http://localhost:5002';
const FLASK_API_KEY = process.env.FLASK_API_KEY || 'eventheodds-flask-api-key-2025';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    // Validate request
    const validationResult = aiLawyerRequestSchema.safeParse(body);
    if (!validationResult.success) {
      return NextResponse.json(
        {
          success: false,
          error: validationResult.error.errors[0].message
        },
        { status: 400 }
      );
    }

    const { message, conversationId, history, useRag } = validationResult.data;

    // Choose endpoint based on whether RAG is enabled
    const endpoint = useRag ? '/ask' : '/chat';
    const ragUrl = `${AI_LAWYER_RAG_URL}${endpoint}`;

    // Prepare request body for RAG service
    const ragRequestBody = useRag
      ? {
          question: message,
          conversation_id: conversationId,
          history: history || []
        }
      : {
          message: message,
          history: history || []
        };

    // Call AI Lawyer RAG service
    const ragResponse = await fetch(ragUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': FLASK_API_KEY
      },
      body: JSON.stringify(ragRequestBody)
    });

    if (!ragResponse.ok) {
      const errorText = await ragResponse.text();
      console.error(`AI Lawyer RAG Error: ${ragResponse.status} - ${errorText}`);

      // Return graceful error response
      return NextResponse.json({
        success: false,
        error: 'AI Lawyer service temporarily unavailable',
        message: 'I apologize, but I\'m having trouble accessing the legal knowledge base. Please try again in a moment.',
        disclaimer: 'This AI provides legal information for educational purposes only. Please consult a licensed attorney for legal advice.'
      }, { status: 503 });
    }

    const ragData = await ragResponse.json();

    // Format response for frontend
    return NextResponse.json({
      success: true,
      message: ragData.answer || ragData.response,
      sources: ragData.sources || [],
      documentsSearched: ragData.documents_searched || 0,
      relevantFound: ragData.relevant_found || 0,
      conversationId: conversationId || generateConversationId(),
      disclaimer: 'This information is for educational purposes only and does not constitute legal advice. Please consult a licensed attorney for advice specific to your situation.'
    });

  } catch (error) {
    console.error('AI Lawyer API Error:', error);

    return NextResponse.json({
      success: false,
      error: 'Internal server error',
      message: 'I encountered an unexpected error. Please try again.',
      disclaimer: 'This AI provides legal information for educational purposes only.'
    }, { status: 500 });
  }
}

// GET endpoint for service status
export async function GET() {
  try {
    const statusUrl = `${AI_LAWYER_RAG_URL}/status`;

    const response = await fetch(statusUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.ok) {
      const data = await response.json();
      return NextResponse.json({
        success: true,
        status: 'online',
        service: 'AI Lawyer Chat',
        ragService: data
      });
    } else {
      return NextResponse.json({
        success: false,
        status: 'offline',
        service: 'AI Lawyer Chat',
        error: 'RAG service not responding'
      }, { status: 503 });
    }

  } catch (error) {
    return NextResponse.json({
      success: false,
      status: 'offline',
      service: 'AI Lawyer Chat',
      error: 'Failed to connect to RAG service'
    }, { status: 503 });
  }
}

// Helper function to generate conversation ID
function generateConversationId(): string {
  return `legal-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
