// app/api/frontend/ai-scholarship-match/match/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import pool from "../../../../../lib/db/db";

const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || '';

export async function POST(request: NextRequest) {
  let connection;

    const comingHeaders = request.headers.get("authorization");
  if (comingHeaders !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: 'Unauthorized Access' },
      { status: 401 }
    );
  }
  
  try {
    const body = await request.json();
    const { 
      fullName, email, phone, nationality, age,
      educationLevel, fieldOfStudy, cgpa,
      englishTest, englishScore,
      preferredCountries, scholarshipType, fundingPriority,
      limit = 32
    } = body;

    console.log('📥 Received match request:', { fullName, email, fieldOfStudy, cgpa, preferredCountries });

    if (!fullName || !email) {
      return NextResponse.json(
        { success: false, message: 'Name and email are required' },
        { status: 400 }
      );
    }

    connection = await pool.getConnection();

    // Get all active scholarships
    const [scholarships] = await connection.query(`
      SELECT 
        s.id,
        s.slug,
        s.title,
        s.amount_min,
        s.amount_max,
        s.deadline,
        s.description,
        s.percentage_cover,
        s.cgpa as required_cgpa,
        s.ielts,
        c.country as country_name,
        c.currency_symbol,
        GROUP_CONCAT(DISTINCT p.title SEPARATOR ', ') as qualifications
      FROM scholarships s
      LEFT JOIN countries c ON s.country_id = c.id
      LEFT JOIN scholarship_qualifications sq ON s.id = sq.scholarship_id
      LEFT JOIN posts p ON sq.qualification_id = p.id AND p.post_type = 1
      WHERE s.is_active = 1
        AND (s.deadline IS NULL OR s.deadline >= CURDATE())
      GROUP BY s.id, s.title, s.description, s.cgpa, s.percentage_cover, s.ielts, 
               c.country, c.currency_symbol, s.amount_min, s.amount_max, s.deadline, s.slug
      ORDER BY 
        CASE WHEN s.cgpa IS NULL THEN 1 ELSE 0 END DESC,
        s.cgpa ASC,
        s.percentage_cover DESC,
        COALESCE(s.amount_max, s.amount_min, 0) DESC
      LIMIT ?
    `, [limit * 2]);

    console.log('📊 Found scholarships:', scholarships?.length);

    if (!scholarships || scholarships.length === 0) {
      return NextResponse.json({
        success: true,
        scholarships: [],
        analysis: null,
        message: 'No scholarships found'
      });
    }

    // Calculate student data
    const studentCGPA = parseFloat(cgpa?.toString?.() || cgpa || '0');
    const studentEnglishScore = parseFloat(englishScore?.toString?.() || englishScore || '0');
    const preferredCountriesList = preferredCountries || [];

    // Calculate match scores
    const scoredScholarships = scholarships.map((sch: any) => {
      let matchScore = 60;
      const requiredCGPA = parseFloat(sch.required_cgpa) || 0;
      
      // GPA Match (25 points)
      if (requiredCGPA === 0) {
        matchScore += 25;
      } else if (studentCGPA >= requiredCGPA) {
        matchScore += 25;
      } else if (studentCGPA >= (requiredCGPA - 0.3)) {
        matchScore += 18;
      } else if (studentCGPA >= (requiredCGPA - 0.5)) {
        matchScore += 12;
      } else if (studentCGPA > 0) {
        matchScore += 5;
      }
      
      // Field of Study Match (20 points)
      const studentField = fieldOfStudy?.toLowerCase() || '';
      const scholarshipText = `${sch.title} ${sch.description}`.toLowerCase();
      if (studentField && scholarshipText.includes(studentField)) {
        matchScore += 20;
      } else if (studentField) {
        const relatedFields = getRelatedFields(studentField);
        if (relatedFields.some(f => scholarshipText.includes(f))) {
          matchScore += 12;
        }
      }
      
      // Country Match (20 points)
      const scholarshipCountry = sch.country_name?.toLowerCase() || '';
      if (preferredCountriesList.length > 0) {
        const isPreferred = preferredCountriesList.some(country => 
          scholarshipCountry.includes(country.toLowerCase())
        );
        if (isPreferred) {
          matchScore += 20;
        } else {
          matchScore += 5;
        }
      } else {
        matchScore += 10;
      }
      
      // Funding Match (15 points)
      const scholarshipCover = sch.percentage_cover || 0;
      if (fundingPriority === 'full' && scholarshipCover >= 75) {
        matchScore += 15;
      } else if (fundingPriority === 'partial' && scholarshipCover >= 25 && scholarshipCover < 75) {
        matchScore += 15;
      } else if (fundingPriority === 'any') {
        matchScore += 10;
      }
      
      // Language Match (10 points)
      if (sch.ielts === 0) {
        matchScore += 10;
      } else if (studentEnglishScore >= 7.0) {
        matchScore += 10;
      } else if (studentEnglishScore >= 6.5) {
        matchScore += 7;
      } else if (studentEnglishScore >= 6.0) {
        matchScore += 5;
      }
      
      // Deadline bonus (5 points)
      try {
        if (sch.deadline && sch.deadline !== 'Rolling Admission') {
          const deadline = new Date(sch.deadline);
          const now = new Date();
          const diffDays = Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
          if (diffDays > 0 && diffDays <= 90) {
            matchScore += Math.min(5, Math.floor(diffDays / 20));
          }
        }
      } catch (e) {}
      
      matchScore = Math.max(40, Math.min(100, Math.round(matchScore)));
      
      // Parse qualifications
      const qualifications = sch.qualifications ? 
        sch.qualifications.split(', ').filter((q: string) => q) : [];
      
      return {
        id: sch.id,
        title: sch.title,
        slug: sch.slug,
        country: sch.country_name || 'International',
        amount_min: sch.amount_min,
        amount_max: sch.amount_max,
        amount: calculateAmount(sch.amount_min, sch.amount_max),
        deadline: sch.deadline || 'Rolling Admission',
        matchScore: matchScore,
        type: getScholarshipType(sch.percentage_cover),
        description: truncateDescription(sch.description || '', 200),
        eligibility: generateEligibility(sch, studentCGPA),
        aiInsight: generateBasicInsight(sch, matchScore, studentCGPA, requiredCGPA),
        link: sch.slug ? `/scholarships/${sch.slug}` : `/scholarships/${sch.id}`,
        tags: generateTags(sch, matchScore),
        percentage_cover: sch.percentage_cover,
        required_cgpa: sch.required_cgpa?.toString(),
        ielts: sch.ielts,
        currency_symbol: sch.currency_symbol || '$',
        qualifications: qualifications
      };
    });
    
    // Sort by match score
    const sortedScholarships = scoredScholarships.sort((a, b) => b.matchScore - a.matchScore);
    const topScholarships = sortedScholarships.slice(0, limit);
    
    // Get DeepSeek AI analysis
    let analysis = calculateProfileAnalysis({
      fullName, email, nationality, age,
      educationLevel, fieldOfStudy, cgpa: studentCGPA,
      englishScore: studentEnglishScore,
      preferredCountries: preferredCountriesList,
      fundingPriority
    }, topScholarships);
    
    // Enhance with DeepSeek if available
    if (DEEPSEEK_API_KEY) {
      try {
        const deepSeekResult = await getDeepSeekAnalysis({
          profile: {
            fieldOfStudy,
            cgpa: studentCGPA,
            englishScore: studentEnglishScore,
            preferredCountries: preferredCountriesList,
            fundingPriority,
            educationLevel,
            nationality,
            age
          },
          scholarships: topScholarships,
          matchedCount: topScholarships.length
        });
        
        if (deepSeekResult) {
          analysis = {
            ...analysis,
            strengths: deepSeekResult.strengths || analysis.strengths,
            weaknesses: deepSeekResult.weaknesses || analysis.weaknesses,
            recommendations: deepSeekResult.recommendations || analysis.recommendations,
            aiInsights: deepSeekResult.aiInsights || analysis.aiInsights,
            competitiveAnalysis: deepSeekResult.competitiveAnalysis || analysis.competitiveAnalysis
          };
        }
      } catch (aiError) {
        console.error('DeepSeek analysis error:', aiError);
      }
    }
    
    console.log('✅ Found matches:', topScholarships.length);
    
    return NextResponse.json({
      success: true,
      scholarships: topScholarships,
      analysis: analysis,
      total: topScholarships.length
    });
    
  } catch (error: any) {
    console.error('❌ Scholarship match error:', error);
    return NextResponse.json({
      success: false,
      message: error.message || 'Internal server error',
      scholarships: [],
      analysis: null
    }, { status: 500 });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

// DeepSeek Analysis Integration
async function getDeepSeekAnalysis(data: any): Promise<any> {
  const prompt = `You are an expert scholarship advisor. Analyze this student profile and provide a comprehensive analysis.

STUDENT PROFILE:
- Name: ${data.profile.fullName || 'Not specified'}
- Education Level: ${data.profile.educationLevel || 'Not specified'}
- Field of Study: ${data.profile.fieldOfStudy || 'Not specified'}
- GPA/CGPA: ${data.profile.cgpa || 'Not specified'}
- Language Score: ${data.profile.englishScore || 'Not specified'}
- Nationality: ${data.profile.nationality || 'Not specified'}
- Age: ${data.profile.age || 'Not specified'}

PREFERENCES:
- Preferred Countries: ${data.profile.preferredCountries?.join(', ') || 'Any'}
- Funding Priority: ${data.profile.fundingPriority || 'Any'}

RESULTS:
- ${data.matchedCount} scholarships found matching this profile
- Average match score: ${Math.round(data.scholarships.reduce((sum: number, s: any) => sum + s.matchScore, 0) / data.scholarships.length)}%

Based on this information, provide a detailed analysis with:

1. KEY STRENGTHS (3-4 bullet points)
2. AREAS FOR IMPROVEMENT (3-4 bullet points)
3. RECOMMENDATIONS (4-5 actionable steps with priority levels)
4. AI INSIGHTS (3-4 key observations about the student's profile)

Return as JSON with keys: strengths, weaknesses, recommendations, aiInsights.`;

  const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
    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 scholarship advisor. Provide concise, actionable insights in JSON format.'
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      max_tokens: 1000,
      temperature: 0.7
    })
  });

  const result = await response.json();
  const content = result?.choices?.[0]?.message?.content || '';
  
  try {
    const cleanContent = content.replace(/```json\n?|\n?```/g, '').trim();
    return JSON.parse(cleanContent);
  } catch (parseError) {
    console.error('Failed to parse DeepSeek response:', parseError);
    return null;
  }
}

// Helper Functions
function getRelatedFields(field: string): string[] {
  const relatedMap: Record<string, string[]> = {
    'computer science': ['cs', 'software', 'programming', 'it', 'computing', 'data science'],
    'engineering': ['technology', 'technical', 'mechanical', 'electrical', 'civil'],
    'business': ['management', 'administration', 'commerce', 'finance', 'marketing', 'economics'],
    'medicine': ['medical', 'health', 'healthcare', 'nursing', 'pharmacy'],
    'arts': ['humanities', 'liberal arts', 'creative arts', 'design'],
    'science': ['natural sciences', 'physics', 'chemistry', 'biology', 'mathematics']
  };
  
  const lowerField = field.toLowerCase();
  for (const [key, values] of Object.entries(relatedMap)) {
    if (lowerField.includes(key) || key.includes(lowerField)) {
      return values;
    }
  }
  return [];
}

function calculateAmount(min?: number | string, max?: number | string): number {
  const minNum = min !== undefined && min !== null ? Number(min) : null;
  const maxNum = max !== undefined && max !== null ? Number(max) : null;
  
  if (minNum !== null && maxNum !== null && minNum !== maxNum) {
    return Math.round((minNum + maxNum) / 2);
  }
  if (minNum !== null) return minNum;
  if (maxNum !== null) return maxNum;
  return Math.floor(Math.random() * 30000) + 10000;
}

function getScholarshipType(percentage?: number): string {
  if (!percentage) return 'variable';
  if (percentage === 100) return 'full_tuition';
  if (percentage >= 75) return 'fully_funded';
  if (percentage >= 50) return 'partial';
  return 'financial_aid';
}

function truncateDescription(description: string, maxLength: number = 200): string {
  const plainText = description?.replace(/<[^>]*>/g, '') || '';
  if (plainText.length <= maxLength) return plainText;
  return plainText.substring(0, maxLength) + '...';
}

function generateBasicInsight(sch: any, matchScore: number, studentCGPA: number, requiredCGPA: number): string {
  const insights = [];
  
  if (requiredCGPA === 0) {
    insights.push('No GPA requirement');
  } else if (studentCGPA >= requiredCGPA) {
    insights.push('Meets GPA requirements');
  } else if (studentCGPA >= (requiredCGPA - 0.3)) {
    insights.push('Close to GPA requirement');
  }
  
  if (sch.percentage_cover && sch.percentage_cover >= 75) {
    insights.push('High funding coverage');
  } else if (sch.percentage_cover && sch.percentage_cover >= 50) {
    insights.push('Good funding opportunity');
  }
  
  if (matchScore >= 80) {
    insights.unshift('Excellent match for your profile');
  } else if (matchScore >= 70) {
    insights.unshift('Strong match worth applying');
  } else if (matchScore >= 60) {
    insights.unshift('Consider if you meet all requirements');
  }
  
  return insights.length > 0 ? insights.join(' • ') : 'Review requirements carefully';
}

function generateEligibility(sch: any, studentCGPA: number): string[] {
  const eligibility = [];
  
  if (sch.required_cgpa) {
    const requiredCGPA = parseFloat(sch.required_cgpa);
    eligibility.push(`GPA: ${requiredCGPA}${studentCGPA >= requiredCGPA ? ' ✓' : ''}`);
  } else {
    eligibility.push('GPA: Not specified');
  }
  
  if (sch.ielts === 1) {
    eligibility.push('IELTS Required');
  } else if (sch.ielts === 0) {
    eligibility.push('No IELTS Required ✓');
  }
  
  if (sch.percentage_cover) {
    eligibility.push(`${sch.percentage_cover}% Covered`);
  }
  
  if (sch.deadline && sch.deadline !== 'Rolling Admission') {
    try {
      const deadline = new Date(sch.deadline);
      eligibility.push(`Deadline: ${deadline.toLocaleDateString()}`);
    } catch (e) {
      eligibility.push(`Deadline: ${sch.deadline}`);
    }
  }
  
  if (sch.qualifications) {
    eligibility.push(`Level: ${sch.qualifications.split(',').slice(0, 2).join(', ')}`);
  }
  
  return eligibility.slice(0, 4);
}

function generateTags(sch: any, matchScore: number): string[] {
  const tags = [];
  
  if (sch.percentage_cover === 100) tags.push('Full Tuition');
  else if (sch.percentage_cover && sch.percentage_cover >= 75) tags.push('Fully Funded');
  else if (sch.percentage_cover && sch.percentage_cover >= 50) tags.push('Partial');
  
  if (sch.ielts === 0) tags.push('No IELTS');
  
  if (matchScore >= 80) tags.push('Top Match');
  
  if (sch.country_name) tags.push(sch.country_name);
  
  return tags.slice(0, 3);
}

function calculateProfileAnalysis(profile: any, matches: any[]): any {
  const academicScore = calculateAcademicScore(profile.cgpa);
  const completeness = calculateCompleteness(profile);
  const competitiveness = calculateCompetitiveness(profile.cgpa, profile.englishScore);
  
  const overallScore = Math.round(
    (academicScore * 0.40) + 
    (completeness * 0.30) + 
    (competitiveness * 0.30)
  );
  
  const totalFunding = matches.reduce((sum, s) => sum + (s.amount || 0), 0);
  
  return {
    overallScore: overallScore,
    estimatedSuccess: Math.min(95, Math.max(30, overallScore)),
    totalMatches: matches.length,
    totalFunding: `$${totalFunding.toLocaleString()}`,
    profileStrength: {
      academic: academicScore,
      profileCompleteness: completeness,
      competitiveness: competitiveness,
      readiness: Math.round((academicScore + completeness + competitiveness) / 3)
    },
    strengths: generateProfileStrengths(profile),
    weaknesses: generateProfileWeaknesses(profile),
    recommendations: generateRecommendations(profile),
    aiInsights: generateAIInsights(profile, matches),
    competitiveAnalysis: {
      percentile: calculatePercentile(overallScore),
      strengths: ['Strong academic foundation', 'Clear career goals', 'International perspective'],
      opportunities: ['Research experience', 'Leadership roles', 'Community service']
    }
  };
}

function calculateAcademicScore(cgpa: number): number {
  let score = 50;
  if (cgpa >= 3.8) score += 40;
  else if (cgpa >= 3.5) score += 35;
  else if (cgpa >= 3.0) score += 30;
  else if (cgpa >= 2.5) score += 20;
  else if (cgpa > 0) score += 10;
  return Math.min(100, score);
}

function calculateCompleteness(profile: any): number {
  let filled = 0;
  const fields = ['fullName', 'email', 'educationLevel', 'fieldOfStudy'];
  fields.forEach(f => { if (profile[f]) filled++; });
  if (profile.cgpa > 0) filled++;
  if (profile.preferredCountries?.length > 0) filled++;
  if (profile.fundingPriority) filled++;
  return Math.round((filled / 7) * 100);
}

function calculateCompetitiveness(cgpa: number, englishScore: number): number {
  let score = 60;
  if (cgpa >= 3.5) score += 20;
  else if (cgpa >= 3.0) score += 10;
  if (englishScore >= 7.0) score += 20;
  else if (englishScore >= 6.5) score += 15;
  else if (englishScore >= 6.0) score += 10;
  return Math.min(100, score);
}

function generateProfileStrengths(profile: any): string[] {
  const strengths = [];
  if (profile.cgpa >= 3.5) strengths.push('Strong academic performance');
  if (profile.englishScore >= 7.0) strengths.push('Good English proficiency');
  if (profile.preferredCountries?.length > 0) strengths.push('Clear geographical preferences');
  if (profile.fieldOfStudy) strengths.push(`Specialized in ${profile.fieldOfStudy}`);
  if (strengths.length === 0) strengths.push('Good foundational profile');
  return strengths.slice(0, 3);
}

function generateProfileWeaknesses(profile: any): string[] {
  const weaknesses = [];
  if (profile.cgpa < 3.0 && profile.cgpa > 0) weaknesses.push('GPA below competitive threshold');
  if (profile.englishScore < 6.5 && profile.englishScore > 0) weaknesses.push('English proficiency needs improvement');
  if (!profile.preferredCountries?.length) weaknesses.push('No specific country preferences');
  if (!profile.fundingPriority) weaknesses.push('Funding priority not specified');
  return weaknesses.slice(0, 3);
}

function generateRecommendations(profile: any): any[] {
  const recommendations = [];
  
  if (profile.cgpa < 3.0 && profile.cgpa > 0) {
    recommendations.push({
      priority: 'high',
      action: 'Consider scholarships with lower GPA requirements',
      timeline: 'Immediately',
      impact: 'High'
    });
  }
  
  if (profile.englishScore < 6.5 && profile.englishScore > 0) {
    recommendations.push({
      priority: 'medium',
      action: 'Improve English score to 6.5+ for better opportunities',
      timeline: 'Within 3 months',
      impact: 'Medium'
    });
  }
  
  if (!profile.preferredCountries?.length) {
    recommendations.push({
      priority: 'medium',
      action: 'Specify preferred countries for targeted results',
      timeline: 'Immediately',
      impact: 'Medium'
    });
  }
  
  recommendations.push({
    priority: 'low',
    action: 'Prepare strong recommendation letters',
    timeline: 'Within 2 months',
    impact: 'Medium'
  });
  
  return recommendations.slice(0, 4);
}

function generateAIInsights(profile: any, matches: any[]): string[] {
  const insights = [];
  
  if (matches.length > 10) {
    insights.push(`Found ${matches.length} potential scholarships - focus on top matches`);
  } else if (matches.length > 0) {
    insights.push(`Found ${matches.length} scholarships matching your profile`);
  }
  
  const highMatches = matches.filter(m => m.matchScore >= 80).length;
  if (highMatches > 0) {
    insights.push(`${highMatches} excellent matches identified for your profile`);
  }
  
  if (profile.fundingPriority === 'full') {
    insights.push('Full scholarships are highly competitive - consider partial funding options');
  }
  
  insights.push('Apply early as scholarship deadlines approach quickly');
  
  return insights.slice(0, 3);
}

function calculatePercentile(score: number): number {
  if (score >= 90) return 95;
  if (score >= 80) return 85;
  if (score >= 70) return 70;
  if (score >= 60) return 55;
  return 40;
}