import { NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';

// DeepSeek API integration
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;

async function callDeepSeekAI(prompt) {
  try {
    const response = await fetch(DEEPSEEK_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: [
          {
            role: 'system',
            content: `You are an expert education consultant specializing in university and course comparisons. 
                     Provide detailed, objective analysis to help students make informed decisions.
                     IMPORTANT: You MUST respond with VALID JSON only, following this exact structure:
                     {
                       "overview": "A brief 2-3 paragraph executive summary",
                       "detailed_comparison": {
                         "sections": [
                           {
                             "title": "Section Title",
                             "content": "Section content with bullet points or paragraphs",
                             "key_points": ["Point 1", "Point 2", "Point 3"]
                           }
                         ]
                       },
                       "top_recommendation": {
                         "name": "Name of top recommended item",
                         "reason": "Detailed explanation why this is recommended",
                         "best_for": ["Type of student 1", "Type of student 2"],
                         "strengths": ["Strength 1", "Strength 2"],
                         "considerations": ["Consideration 1", "Consideration 2"]
                       },
                       "comparative_analysis": {
                         "ranking_order": ["First", "Second", "Third"],
                         "key_differences": ["Difference 1", "Difference 2"],
                         "value_analysis": "Analysis of cost vs value"
                       },
                       "final_advice": "Practical next steps and advice"
                     }
                     
                     Format all text to be clean and readable without markdown symbols like ** or ##.
                     Use proper headings in the content sections.
                     Make bullet points clear and well-structured.`
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.7,
        max_tokens: 3000,
        response_format: { type: "json_object" }
      })
    });

    if (!response.ok) {
      throw new Error(`DeepSeek API error: ${response.status}`);
    }

    const data = await response.json();
    return JSON.parse(data.choices[0]?.message?.content || '{}');
  } catch (error) {
    console.error('Error calling DeepSeek AI:', error);
    throw error;
  }
}

function createComparisonPrompt(comparisonData, comparisonType) {
  const dataString = JSON.stringify(comparisonData, null, 2);
  
  if (comparisonType === 'university') {
    return `Analyze and compare these universities. Extract the top recommendation and provide structured analysis:

    UNIVERSITY DATA:
    ${dataString}

    Analyze based on:
    1. Academic ranking (lower is better)
    2. International student population
    3. Language options
    4. Scholarship availability
    5. University reputation
    6. Student diversity
    7. Intake flexibility

    Identify which university is BEST OVERALL and explain why.
    Also mention which might be best for different student types.
    
    Format the response as structured JSON as specified in the system prompt.`;
    
  } else if (comparisonType === 'course') {
    return `Analyze and compare these courses. Extract the top recommendation and provide structured analysis:

    COURSE DATA:
    ${dataString}

    Analyze based on:
    1. Yearly fee and total program cost
    2. Duration of program
    3. Application fees
    4. Scholarship availability
    5. Program reputation
    6. Value for money
    7. Career implications

    Identify which course offers BEST VALUE and explain why.
    Also mention which might be best for different student profiles.
    
    Format the response as structured JSON as specified in the system prompt.`;
  }
  
  return '';
}

// Helper function to clean and format AI response
function formatAIResponse(aiResponse) {
  // If AI response is already a string (old format), try to parse it
  if (typeof aiResponse === 'string') {
    try {
      // Try to extract JSON if it's wrapped in text
      const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        aiResponse = JSON.parse(jsonMatch[0]);
      } else {
        // Fallback to simple structure if no JSON found
        return {
          overview: aiResponse.substring(0, 500) + '...',
          detailed_comparison: {
            sections: [
              {
                title: "Analysis",
                content: aiResponse,
                key_points: []
              }
            ]
          },
          top_recommendation: {
            name: "Analysis incomplete",
            reason: "Could not extract specific recommendation",
            best_for: [],
            strengths: [],
            considerations: []
          },
          comparative_analysis: {
            ranking_order: [],
            key_differences: [],
            value_analysis: ""
          },
          final_advice: "Please refer to the detailed analysis above."
        };
      }
    } catch (error) {
      console.error('Error parsing AI response:', error);
      return null;
    }
  }
  
  return aiResponse;
}

// Function to extract top recommendation from raw data
function extractTopRecommendation(aiAnalysis, comparisonData, comparisonType) {
  if (!aiAnalysis || !aiAnalysis.top_recommendation) {
    // Fallback logic: Find top ranked university or cheapest course
    if (comparisonType === 'university' && comparisonData.length > 0) {
      // Find university with best (lowest) ranking
      const universitiesWithRanking = comparisonData.filter(u => u.ranking && !isNaN(parseInt(u.ranking)));
      if (universitiesWithRanking.length > 0) {
        const topUniversity = universitiesWithRanking.reduce((prev, current) => 
          parseInt(prev.ranking) < parseInt(current.ranking) ? prev : current
        );
        
        return {
          name: topUniversity.name,
          id: topUniversity.id,
          reason: `Highest ranked university (#${topUniversity.ranking}) among the compared options.`,
          best_for: ["Students prioritizing academic prestige and ranking"],
          strengths: ["Strong academic reputation", "Higher ranking"],
          considerations: ["Verify specific program rankings and course fees"]
        };
      }
    } else if (comparisonType === 'course' && comparisonData.length > 0) {
      // Find course with lowest yearly fee
      const coursesWithFee = comparisonData.filter(c => c.yearly_fee && !isNaN(parseInt(c.yearly_fee)));
      if (coursesWithFee.length > 0) {
        const topCourse = coursesWithFee.reduce((prev, current) => 
          parseInt(prev.yearly_fee) < parseInt(current.yearly_fee) ? prev : current
        );
        
        return {
          name: topCourse.name,
          id: topCourse.id,
          reason: `Most affordable option with yearly fee of ${topCourse.yearly_fee}.`,
          best_for: ["Budget-conscious students"],
          strengths: ["Lower cost", "Potentially better value"],
          considerations: ["Consider total program duration and quality"]
        };
      }
    }
    
    return null;
  }
  
  return aiAnalysis.top_recommendation;
}

export async function POST(request) {
  const connection = await pool.getConnection();
  
  try {
    const body = await request.json();
    const { item_ids, comparison_type } = body;
    let comparisonData = [];

    if (comparison_type === "university") {
      // Fetch universities
      const universities = await Promise.all(
        item_ids.map(async (item_id) => {
          try {
            const [getSingleUniversity] = await connection.query(
              `SELECT id, name, average_course_fee, languages, application_fee, university_type, ranking, intake, scholarship, international_student, total_students FROM university_details WHERE id = ? AND is_active = 1`,
              [item_id]
            );
            
            if (getSingleUniversity.length === 0) {
              console.log("No university found with ID:", item_id);
              return null;
            }
            
            return getSingleUniversity[0];
          } catch (error) {
            console.error(`Error fetching university with ID ${item_id}:`, error);
            return null;
          }
        })
      );

      comparisonData = universities.filter(university => university !== null);

    } else if (comparison_type === "course") {
      // Fetch courses
      const courses = await Promise.all(
        item_ids.map(async (item_id) => {
          try {
            const [getSingleCourse] = await connection.query(
              `SELECT id, name, yearly_fee, duration, application_fee, scholarship FROM courses WHERE id = ? AND active = 1`,
              [item_id]
            );
            
            if (getSingleCourse.length === 0) {
              console.log("No course found with ID:", item_id);
              return null;
            }
            
            return getSingleCourse[0];
          } catch (error) {
            console.error(`Error fetching Course with ID ${item_id}:`, error);
            return null;
          }
        })
      );

      comparisonData = courses.filter(course => course !== null);

    } else {
      return NextResponse.json(
        {
          success: false,
          message: 'Invalid comparison type'
        },
        { status: 400 }
      );
    }

    // Check if we have data to compare
    if (comparisonData.length === 0) {
      return NextResponse.json(
        {
          success: false,
          message: 'No valid items found for comparison'
        },
        { status: 404 }
      );
    }

    console.log("Comparison Data:", comparisonData);

    // Call DeepSeek AI for analysis
    const prompt = createComparisonPrompt(comparisonData, comparison_type);
    const rawAIResponse = await callDeepSeekAI(prompt);
    
    // Format the AI response
    const aiAnalysis = formatAIResponse(rawAIResponse);
    
    if (!aiAnalysis) {
      throw new Error('Failed to parse AI response');
    }

    // Extract top recommendation
    const topRecommendation = extractTopRecommendation(aiAnalysis, comparisonData, comparison_type) || {
      name: "Unable to determine",
      reason: "Insufficient data for recommendation",
      best_for: [],
      strengths: [],
      considerations: []
    };

    // Prepare structured response
    const responseData = {
      success: true,
      comparison_type,
      items_count: comparisonData.length,
      raw_data: comparisonData,
      ai_analysis: {
        overview: aiAnalysis.overview || "No overview provided",
        detailed_comparison: aiAnalysis.detailed_comparison || { sections: [] },
        top_recommendation: topRecommendation,
        comparative_analysis: aiAnalysis.comparative_analysis || {
          ranking_order: [],
          key_differences: [],
          value_analysis: ""
        },
        final_advice: aiAnalysis.final_advice || "No specific advice provided."
      },
      metadata: {
        analysis_type: comparison_type === 'university' ? 'university_comparison' : 'course_comparison',
        data_points_analyzed: comparisonData.length,
        recommendation_provided: topRecommendation.name !== "Unable to determine",
        generated_at: new Date().toISOString()
      }
    };

    return NextResponse.json(responseData);
    
  } catch (error) {
    console.error('Error in comparison API:', error);
    
    // Check if it's an AI API error or database error
    const isAIError = error.message?.includes('DeepSeek') || error.message?.includes('AI');
    
    return NextResponse.json(
      { 
        success: false, 
        message: isAIError 
          ? 'Error generating AI analysis. Data fetched successfully.' 
          : 'Error Comparing Universities or Courses',
        data: comparisonData || [], // Return data even if AI fails
        error: process.env.NODE_ENV === 'development' ? error.message : undefined 
      },
      { status: isAIError ? 502 : 500 }
    );
  } finally {
    // Always release the connection back to the pool
    if (connection) {
      connection.release();
    }
  }
}