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 || '';

// Types
interface PersonalInfo {
  fullName?: string;
  email?: string;
  age?: string;
  nationality?: string;
  currentCountry?: string;
}

interface AcademicInfo {
  educationLevel?: string;
  cgpa?: string;
  fieldOfStudy?: string;
  languageScore?: string;
  researchExperience?: string;
  publications?: string;
  awards?: string;
}

interface Preferences {
  countries?: string[];
  degreeLevel?: string;
  scholarshipType?: string;
  fundingPriority: 'full' | 'partial' | 'any';
}

interface EnhancedProfile {
  personal?: PersonalInfo;
  academic?: AcademicInfo;
  preferences?: Preferences;
}

interface Scholarship {
  id: number;
  title: string;
  slug?: string;
  country: string;
  amount: number;
  deadline: string;
  matchScore: number;
  type: string;
  description: string;
  eligibility: string[];
  aiInsight: string;
  link: string;
  tags?: string[];
  percentage_cover?: number;
  required_cgpa?: string;
  ielts?: number;
  currency_symbol?: string;
  fieldOfStudy?: string;
  amount_min?: number;
  amount_max?: number;
  qualifications?: string[];
}

interface Analysis {
  overallScore: number;
  strengths: string[];
  weaknesses: string[];
  recommendations: string[];
  estimatedSuccess: number;
  totalMatches: number;
  totalFunding: string;
  profileStrength: {
    academic: number;
    profileCompleteness: number;
    competitiveness: number;
    readiness: number;
  };
  riskFactors: {
    factor: string;
    likelihood: 'high' | 'medium' | 'low';
    impact: 'high' | 'medium' | 'low';
    mitigation: string;
  }[];
  timelineRecommendations: string[];
  scholarshipCategories: {
    highMatch: number;
    mediumMatch: number;
    lowMatch: number;
  };
  matchBreakdown?: {
    academicMatch: number;
    countryMatch: number;
    fundingMatch: number;
    timelineMatch: number;
  };
  aiInsights?: string[];
  competitiveAnalysis?: {
    percentile: number;
    strengths: string[];
    opportunities: string[];
  };
}

export async function POST(request: NextRequest) {
  let connection;
  
  try {
    const body = await request.json();
    const { 
      profile, 
      action, 
      enhanced = true,
      advanced = false,
      query,
      message,
      history = [],
      tokensOptimized = false,
      lead,
      searchType
    }: { 
      profile: EnhancedProfile; 
      action: string; 
      enhanced?: boolean;
      advanced?: boolean;
      query?: string;
      message?: string;
      history?: any[];
      tokensOptimized?: boolean;
      lead?: any;
      searchType?: string;
    } = body;

    console.log('API Request:', { action, query, profileExists: !!profile, leadExists: !!lead });

    // For search action, handle empty query
    if (action === 'search' && !query && !message) {
      return NextResponse.json(
        { success: false, error: 'Search query is required' },
        { status: 400 }
      );
    }

    // For find_matches, profile is required
    if (action === 'find_matches' && !profile) {
      return NextResponse.json(
        { success: false, error: 'Profile is required for matching' },
        { status: 400 }
      );
    }

    connection = await pool.getConnection();

    switch (action) {
      case 'find_matches':
        const matches = await findEnhancedScholarshipMatches(profile, connection, tokensOptimized);
        return NextResponse.json({
          success: true,
          data: matches
        });

      case 'analyze':
        const analysis = await analyzeEnhancedProfileWithDeepSeek(profile, connection);
        return NextResponse.json({
          success: true,
          data: analysis
        });

      case 'search':
        console.log('Processing search action for query:', query);
        const searchResults = await intelligentSearch(query!, profile, connection);
        return NextResponse.json({
          success: true,
          data: searchResults.data,
          insights: searchResults.insights,
          aiSummary: searchResults.aiSummary
        });

      default:
        return NextResponse.json(
          { success: false, error: 'Invalid action' },
          { status: 400 }
        );
    }

  } catch (error: any) {
    console.error('API error:', error);
    
    return NextResponse.json({
      success: false,
      error: error?.message || 'Internal server error',
      data: []
    }, { status: 500 });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

async function findEnhancedScholarshipMatches(profile: EnhancedProfile, connection: any, tokensOptimized: boolean): Promise<Scholarship[]> {
  try {
    // Use DeepSeek-powered matching if available
    if (DEEPSEEK_API_KEY) {
      try {
        const aiMatches = await findScholarshipsWithDeepSeek(profile, connection, tokensOptimized ? 20 : 30);
        if (aiMatches && aiMatches.length > 0) {
          console.log('DeepSeek found', aiMatches.length, 'AI-powered matches');
          return aiMatches;
        }
      } catch (aiError) {
        console.error('DeepSeek matching failed:', aiError);
      }
    }
    
    // Enhanced SQL matching with GPA accommodation
    return await findScholarshipsWithIntelligentSQL(profile, connection, tokensOptimized);
  } catch (error) {
    console.error('Error finding enhanced matches:', error);
    return getFallbackScholarships(profile);
  }
}

async function findScholarshipsWithDeepSeek(profile: EnhancedProfile, connection: any, limit: number): Promise<Scholarship[]> {
  try {
    // Get all active scholarships with qualifications
    const [allScholarships] = 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 
        s.percentage_cover DESC,
        COALESCE(s.amount_max, s.amount_min, 0) DESC,
        CASE WHEN s.cgpa IS NULL THEN 1 ELSE 0 END,
        s.cgpa ASC
      LIMIT 50
    `);

    if (!allScholarships || allScholarships.length === 0) {
      throw new Error('No scholarships found in database');
    }

    // Prepare profile summary for AI
    const profileSummary = `
STUDENT PROFILE:
• Field of Study: ${profile?.academic?.fieldOfStudy || 'Not specified'}
• GPA: ${profile?.academic?.cgpa || 'N/A'} (on 4.0 scale)
• Language Score: ${profile?.academic?.languageScore || 'N/A'} (IELTS/TOEFL)
• Education Level: ${profile?.academic?.educationLevel || 'Not specified'}
• Research Experience: ${profile?.academic?.researchExperience || 'None'}
• Awards: ${profile?.academic?.awards || 'None'}

PREFERENCES:
• Target Countries: ${profile?.preferences?.countries?.join(', ') || 'Any country'}
• Degree Level: ${profile?.preferences?.degreeLevel || 'Any'}
• Funding Priority: ${profile?.preferences?.fundingPriority || 'Any'}

IMPORTANT: Student has GPA 2.0. Find scholarships that accept lower GPAs or don't specify GPA requirements.
    `;

    // Prepare scholarships data for AI
    const scholarshipsForAI = allScholarships.map((sch: any) => ({
      id: sch.id,
      title: sch.title,
      description: truncateDescription(sch.description, 100),
      country: sch.country_name,
      required_gpa: sch.required_cgpa || 'Not specified',
      ielts_required: sch.ielts === 1,
      funding_percentage: sch.percentage_cover || 0,
      amount_range: `${sch.amount_min || 0} - ${sch.amount_max || 0}`,
      deadline: sch.deadline || 'Rolling',
      qualifications: sch.qualifications || 'None'
    }));

    // Call DeepSeek for intelligent matching
    const prompt = `As an expert scholarship advisor, find the BEST matches for this student from the available scholarships.

${profileSummary}

AVAILABLE SCHOLARSHIPS (${scholarshipsForAI.length}):
${JSON.stringify(scholarshipsForAI, null, 2)}

CRITICAL: The student has GPA 2.0. Prioritize:
1. Scholarships with NO GPA requirement (cgpa is NULL)
2. Scholarships with LOW GPA requirements (cgpa <= 2.5)
3. Scholarships that don't specify GPA

Also consider:
- Field of study match (Engineering)
- Country preferences (China, Germany)
- Language requirements (IELTS 6.0)
- Funding needs

Return ONLY JSON with this structure:
{
  "ranked_scholarships": [
    {
      "id": number,
      "match_score": 0-100,
      "match_reason": "brief explanation focusing on why it's suitable for GPA 2.0 student"
    }
  ],
  "gpa_friendly_count": number,
  "recommendations": ["string"]
}

Select top 20-25 best matches.`;

    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 who specializes in finding opportunities for students with lower GPAs. Focus on realistic, accessible scholarships.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        max_tokens: 3000,
        temperature: 0.3,
        response_format: { type: "json_object" }
      })
    });

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

    const data = await response.json();
    const content = data?.choices?.[0]?.message?.content || '';
    
    let rankedResults: any[] = [];
    try {
      const parsed = JSON.parse(content);
      rankedResults = parsed.ranked_scholarships || [];
    } catch (parseError) {
      console.error('Failed to parse DeepSeek response:', parseError);
      throw new Error('Could not parse AI response');
    }

    if (rankedResults.length === 0) {
      throw new Error('No ranked results from AI');
    }

    // Get full scholarship data for ranked IDs
    const rankedIds = rankedResults.map((r: any) => r.id);
    const idPlaceholders = rankedIds.map(() => '?').join(',');
    
    const [rankedScholarships] = 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.id IN (${idPlaceholders})
      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 FIELD(s.id, ${idPlaceholders})
      LIMIT ?
    `, [...rankedIds, ...rankedIds, limit]);

    // Create enhanced scholarship objects
    const enhancedScholarships = await Promise.all(
      rankedScholarships.map(async (scholarship: any) => {
        const aiRank = rankedResults.find((r: any) => r.id === scholarship.id);
        const baseScore = aiRank?.match_score || calculateIntelligentMatchScore(profile, scholarship);
        
        // Adjust score based on GPA compatibility
        let finalScore = adjustScoreForGPA(baseScore, profile, scholarship);
        
        // Generate AI insight
        const aiInsight = await generateGPAFriendlyInsight(
          profile, 
          scholarship, 
          finalScore,
          aiRank?.match_reason || ''
        );

        // Create scholarship link
        const scholarshipLink = scholarship.slug 
          ? `/scholarships/${scholarship.slug}`
          : `/scholarships/${scholarship.id}`;

        // Parse qualifications
        const qualifications = scholarship.qualifications ? 
          scholarship.qualifications.split(', ').filter((q: string) => q) : [];

        return {
          id: scholarship.id,
          title: scholarship.title,
          slug: scholarship.slug,
          country: scholarship.country_name || 'International',
          amount: calculateAmount(scholarship.amount_min, scholarship.amount_max),
          amount_min: scholarship.amount_min,
          amount_max: scholarship.amount_max,
          deadline: scholarship.deadline || 'Rolling Admission',
          matchScore: Math.round(finalScore),
          type: getScholarshipType(scholarship.percentage_cover),
          description: truncateDescription(scholarship.description || '', 150),
          eligibility: generateEnhancedEligibility(scholarship, profile),
          aiInsight: aiInsight,
          link: scholarshipLink,
          tags: generateScholarshipTags(scholarship, profile, qualifications),
          percentage_cover: scholarship.percentage_cover,
          required_cgpa: scholarship.required_cgpa,
          ielts: scholarship.ielts,
          currency_symbol: scholarship.currency_symbol,
          fieldOfStudy: profile?.academic?.fieldOfStudy,
          qualifications: qualifications
        };
      })
    );

    // Sort by match score
    return enhancedScholarships.sort((a, b) => b.matchScore - a.matchScore);

  } catch (error) {
    console.error('DeepSeek matching error:', error);
    throw error;
  }
}

async function findScholarshipsWithIntelligentSQL(profile: EnhancedProfile, connection: any, tokensOptimized: boolean): Promise<Scholarship[]> {
  try {
    // Get profile preferences
    const preferredCountries = profile?.preferences?.countries || [];
    const studentField = (profile?.academic?.fieldOfStudy || '').toLowerCase();
    const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const fundingPriority = profile?.preferences?.fundingPriority || 'any';
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    const degreeLevel = profile?.preferences?.degreeLevel || '';

    // GPA-friendly search: prioritize scholarships without GPA requirements or with low requirements
    const conditions = ['s.is_active = 1', '(s.deadline IS NULL OR s.deadline >= CURDATE())'];
    const params: any[] = [];
    
    // Field of study matching
    if (studentField) {
      // Search in title, description, and qualifications
      conditions.push(`
        (LOWER(s.title) LIKE ? 
         OR LOWER(s.description) LIKE ? 
         OR EXISTS (
           SELECT 1 FROM scholarship_qualifications sq2 
           LEFT JOIN posts p2 ON sq2.qualification_id = p2.id AND p2.post_type = 1
           WHERE sq2.scholarship_id = s.id 
           AND LOWER(p2.title) LIKE ?
         )
        )
      `);
      const fieldPattern = `%${studentField}%`;
      params.push(fieldPattern, fieldPattern, fieldPattern);
    }

    // Country preferences (optional to get more results)
    if (preferredCountries.length > 0) {
      const countryConditions = preferredCountries.map(() => 'LOWER(c.country) LIKE ?');
      conditions.push(`(${countryConditions.join(' OR ')})`);
      params.push(...preferredCountries.map(c => `%${c.toLowerCase()}%`));
    }

    // Degree level matching through qualifications
    if (degreeLevel) {
      const degreeKeywords = getDegreeKeywords(degreeLevel);
      if (degreeKeywords.length > 0) {
        conditions.push(`
          (LOWER(s.title) LIKE ? 
           OR LOWER(s.description) LIKE ? 
           OR EXISTS (
             SELECT 1 FROM scholarship_qualifications sq3 
             LEFT JOIN posts p3 ON sq3.qualification_id = p3.id AND p3.post_type = 1
             WHERE sq3.scholarship_id = s.id 
             AND (${degreeKeywords.map(() => 'LOWER(p3.title) LIKE ?').join(' OR ')})
           )
          )
        `);
        params.push(`%${degreeLevel}%`, `%${degreeLevel}%`);
        params.push(...degreeKeywords.map(kw => `%${kw}%`));
      }
    }

    // GPA-friendly filtering: prioritize scholarships without GPA requirements or with low requirements
    // Don't exclude based on GPA - instead, we'll score them lower
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    const limit = tokensOptimized ? 25 : 40;

    // Query with GPA-friendly ordering
    const 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,
        -- GPA friendliness score (higher for no GPA requirement or low GPA)
        CASE 
          WHEN s.cgpa IS NULL THEN 100
          WHEN s.cgpa <= 2.0 THEN 90
          WHEN s.cgpa <= 2.5 THEN 70
          WHEN s.cgpa <= 3.0 THEN 50
          ELSE 30
        END as gpa_friendliness,
        -- Field match score
        ${studentField ? `
          CASE 
            WHEN LOWER(s.title) LIKE ? THEN 80
            WHEN LOWER(s.description) LIKE ? THEN 60
            WHEN EXISTS (
              SELECT 1 FROM scholarship_qualifications sq4 
              LEFT JOIN posts p4 ON sq4.qualification_id = p4.id AND p4.post_type = 1
              WHERE sq4.scholarship_id = s.id 
              AND LOWER(p4.title) LIKE ?
            ) THEN 70
            ELSE 0
          END as field_match_score,
        ` : '0 as field_match_score,'}
        -- Country match score
        ${preferredCountries.length > 0 ? `
          CASE 
            ${preferredCountries.map((c, i) => `WHEN LOWER(c.country) LIKE '%${c.toLowerCase()}%' THEN ${80 - (i * 10)}`).join('\n')}
            ELSE 20
          END as country_match_score
        ` : '20 as country_match_score'}
      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
      ${whereClause}
      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 
        gpa_friendliness DESC,
        field_match_score DESC,
        country_match_score DESC,
        s.percentage_cover DESC,
        COALESCE(s.amount_max, s.amount_min, 0) DESC
      LIMIT ?
    `;

    // Add field pattern for scoring if studentField exists
    const queryParams = [...params];
    if (studentField) {
      const fieldPattern = `%${studentField}%`;
      queryParams.push(fieldPattern, fieldPattern, fieldPattern);
    }
    queryParams.push(limit);

    console.log('Intelligent SQL query with GPA-friendly matching');
    
    const [scholarships] = await connection.query(query, queryParams) as RowDataPacket[][];

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

    if (!scholarships || scholarships.length === 0) {
      return getFallbackScholarships(profile);
    }

    // Process and intelligently score scholarships
    const matches = await Promise.all(
      scholarships.map(async (scholarship) => {
        // Calculate intelligent match score considering GPA 2.0
        let matchScore = calculateIntelligentMatchScore(profile, scholarship);
        
        // GPA-specific adjustments
        matchScore = adjustScoreForGPA(matchScore, profile, scholarship);
        
        // Country preference (20 points)
        if (preferredCountries.length > 0) {
          const scholarshipCountry = scholarship.country_name?.toLowerCase() || '';
          if (preferredCountries.some(c => scholarshipCountry.includes(c.toLowerCase()))) {
            matchScore += 15;
          } else {
            matchScore += 5; // Small score for non-preferred
          }
        }

        // Language requirements (15 points)
        if (scholarship.ielts === 0) {
          matchScore += 12;
        } else if (languageScore >= 6.5) {
          matchScore += 15;
        } else if (languageScore >= 6.0) {
          matchScore += 10;
        } else if (languageScore > 0) {
          matchScore += 5;
        }

        // Funding match (15 points)
        const scholarshipCover = scholarship.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;
        }

        // Deadline bonus (5 points for upcoming deadlines)
        try {
          if (scholarship.deadline && scholarship.deadline !== 'Rolling Admission') {
            const deadline = new Date(scholarship.deadline);
            const now = new Date();
            const diffDays = Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
            if (diffDays > 0 && diffDays <= 90) {
              matchScore += Math.max(0, 8 - Math.floor(diffDays / 12));
            }
          }
        } catch (e) {
          // Ignore date errors
        }

        // Amount bonus (5 points for high-value scholarships)
        const amount = calculateAmount(scholarship.amount_min, scholarship.amount_max);
        if (amount > 40000) matchScore += 5;
        else if (amount > 20000) matchScore += 3;

        // Normalize score to 40-95 range
        matchScore = Math.max(40, Math.min(95, matchScore));

        // Parse qualifications
        const qualifications = scholarship.qualifications ? 
          scholarship.qualifications.split(', ').filter((q: string) => q) : [];

        // Generate intelligent AI insight
        let aiInsight = generateIntelligentAiInsight(profile, scholarship, matchScore, qualifications);
        
        // Try to get DeepSeek insight if available
        if (DEEPSEEK_API_KEY && matchScore >= 50) {
          try {
            const deepSeekInsight = await generateGPAFriendlyInsight(
              profile, 
              scholarship, 
              matchScore,
              ''
            );
            if (deepSeekInsight) {
              aiInsight = deepSeekInsight;
            }
          } catch (e) {
            // Use default insight
          }
        }

        // Create scholarship link
        const scholarshipLink = scholarship.slug 
          ? `/scholarships/${scholarship.slug}`
          : `/scholarships/${scholarship.id}`;

        return {
          id: scholarship.id,
          title: scholarship.title,
          slug: scholarship.slug,
          country: scholarship.country_name || 'International',
          amount: amount,
          amount_min: scholarship.amount_min,
          amount_max: scholarship.amount_max,
          deadline: scholarship.deadline || 'Rolling Admission',
          matchScore: Math.round(matchScore),
          type: getScholarshipType(scholarship.percentage_cover),
          description: truncateDescription(scholarship.description || '', 150),
          eligibility: generateEnhancedEligibility(scholarship, profile),
          aiInsight: aiInsight,
          link: scholarshipLink,
          tags: generateScholarshipTags(scholarship, profile, qualifications),
          percentage_cover: scholarship.percentage_cover,
          required_cgpa: scholarship.required_cgpa?.toString(),
          ielts: scholarship.ielts,
          currency_symbol: scholarship.currency_symbol,
          fieldOfStudy: studentField,
          qualifications: qualifications
        };
      })
    );

    // Sort by match score
    return matches.sort((a, b) => b.matchScore - a.matchScore);

  } catch (error) {
    console.error('Intelligent SQL matching error:', error);
    return getFallbackScholarships(profile);
  }
}

function calculateIntelligentMatchScore(profile: EnhancedProfile, scholarship: any): number {
  let score = 60; // Base score for all scholarships
  
  const studentField = profile?.academic?.fieldOfStudy?.toLowerCase() || '';
  const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
  const requiredCGPA = parseFloat(scholarship.required_cgpa) || 0;
  
  // Field of study match (25 points)
  if (studentField) {
    const scholarshipText = `${scholarship.title} ${scholarship.description} ${scholarship.qualifications || ''}`.toLowerCase();
    
    if (scholarshipText.includes(studentField)) {
      score += 20;
    } else {
      // Check for related fields
      const relatedFields = getRelatedFields(studentField);
      const hasRelatedField = relatedFields.some(field => scholarshipText.includes(field));
      if (hasRelatedField) {
        score += 15;
      }
    }
  }
  
  // GPA match - INTELLIGENT HANDLING for low GPA (25 points)
  if (requiredCGPA === 0) {
    // No GPA requirement - excellent for low GPA students
    score += 20;
  } else if (studentCGPA >= requiredCGPA) {
    score += 20;
  } else if (studentCGPA >= (requiredCGPA - 0.3)) {
    score += 15;
  } else if (studentCGPA >= (requiredCGPA - 0.5)) {
    score += 10;
  } else if (studentCGPA >= (requiredCGPA - 1.0)) {
    score += 5; // Still give some points for being close
  } else {
    // GPA too low - minimal score but don't exclude completely
    score += 2;
  }
  
  return score;
}

function adjustScoreForGPA(baseScore: number, profile: EnhancedProfile, scholarship: any): number {
  const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
  const requiredCGPA = parseFloat(scholarship.required_cgpa) || 0;
  
  let adjustedScore = baseScore;
  
  // Special adjustments for GPA 2.0 students
  if (studentCGPA === 2.0) {
    if (requiredCGPA === 0) {
      // No GPA requirement - boost score significantly
      adjustedScore += 15;
    } else if (requiredCGPA <= 2.0) {
      // Accepts GPA 2.0 or less - good match
      adjustedScore += 10;
    } else if (requiredCGPA <= 2.5) {
      // Accepts up to 2.5 - okay match
      adjustedScore += 5;
    } else if (requiredCGPA > 3.0) {
      // Requires high GPA - reduce score
      adjustedScore -= 10;
    }
  }
  
  return Math.max(40, Math.min(95, adjustedScore));
}

async function generateGPAFriendlyInsight(profile: EnhancedProfile, scholarship: any, matchScore: number, additionalContext: string = ''): Promise<string> {
  try {
    if (!DEEPSEEK_API_KEY) {
      return generateIntelligentAiInsight(profile, scholarship, matchScore);
    }

    const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const requiredCGPA = parseFloat(scholarship.required_cgpa) || 0;
    
    const prompt = `Generate a helpful, encouraging insight for a scholarship match. The student has GPA ${studentCGPA}.

SCHOLARSHIP:
• ${scholarship.title}
• Location: ${scholarship.country_name || 'International'}
• GPA Requirement: ${requiredCGPA > 0 ? requiredCGPA : 'None specified'}
• IELTS Required: ${scholarship.ielts === 1 ? 'Yes' : 'No'}
• Funding: ${scholarship.percentage_cover || 0}% covered

MATCH SCORE: ${matchScore}%

Focus on:
1. Whether this scholarship is accessible with GPA ${studentCGPA}
2. Any alternative requirements or strengths that could compensate
3. Practical advice for applying
4. Be encouraging but realistic

${additionalContext ? `Additional context: ${additionalContext}` : ''}

Keep it to 1-2 concise, helpful sentences.`;

    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 a supportive scholarship advisor who helps students with various academic backgrounds. Be encouraging and practical.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        max_tokens: 150,
        temperature: 0.7
      })
    });
    
    const data = await response.json();
    const content = data?.choices?.[0]?.message?.content || '';
    
    if (content.trim()) {
      return content.trim();
    }
    
  } catch (error) {
    console.error('GPA-friendly insight error:', error);
  }
  
  return generateIntelligentAiInsight(profile, scholarship, matchScore);
}

function generateIntelligentAiInsight(profile: EnhancedProfile, scholarship: any, matchScore: number, qualifications: string[] = []): string {
  const insights = [];
  
  const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
  const requiredCGPA = parseFloat(scholarship.required_cgpa) || 0;
  const studentField = profile?.academic?.fieldOfStudy?.toLowerCase();
  
  // GPA-focused insights
  if (requiredCGPA === 0) {
    insights.push('No GPA requirement specified');
  } else if (studentCGPA >= requiredCGPA) {
    insights.push('Meets GPA requirements');
  } else if (requiredCGPA - studentCGPA <= 0.5) {
    insights.push('Close to GPA requirements - highlight other strengths');
  } else {
    insights.push('Consider emphasizing other qualifications');
  }
  
  // Field match
  if (studentField) {
    const scholarshipText = `${scholarship.title} ${scholarship.description}`.toLowerCase();
    if (scholarshipText.includes(studentField)) {
      insights.push('Good field match');
    }
  }
  
  // Country preference
  const preferredCountries = profile?.preferences?.countries || [];
  const scholarshipCountry = scholarship.country_name?.toLowerCase() || '';
  if (preferredCountries.some(c => scholarshipCountry.includes(c.toLowerCase()))) {
    insights.push('Matches preferred location');
  }
  
  // Qualifications
  if (qualifications.length > 0) {
    insights.push(`Requirements: ${qualifications.slice(0, 2).join(', ')}`);
  }
  
  // Match score context
  if (matchScore >= 80) {
    insights.unshift('Excellent opportunity');
  } else if (matchScore >= 70) {
    insights.unshift('Good match worth applying');
  } else if (matchScore >= 60) {
    insights.unshift('Consider if other criteria align');
  } else {
    insights.unshift('Review requirements carefully');
  }
  
  return insights.length > 0 ? insights.join(' • ') : 'Review scholarship details for eligibility';
}

// FIXED SEARCH FUNCTION: Properly handles "germany scholarship free" search
async function intelligentSearch(query: string, profile: EnhancedProfile, connection: any): Promise<{ data: Scholarship[], insights: string[], aiSummary?: string }> {
  try {
    console.log('Starting intelligent search for:', query);
    
    const extractedParams = extractSearchParametersWithContext(query, profile);
    console.log('Extracted search params:', extractedParams);
    
    let conditions = ['s.is_active = 1', '(s.deadline IS NULL OR s.deadline >= CURDATE())'];
    let params: any[] = [];
    
    // Handle search for Germany specifically
    const isGermanySearch = query.toLowerCase().includes('germany');
    
    if (isGermanySearch) {
      console.log('Germany search detected, adding Germany filter');
      conditions.push('LOWER(c.country) LIKE ?');
      params.push('%germany%');
    }
    
    // Handle search for "free" scholarships
    const isFreeSearch = query.toLowerCase().includes('free') || 
                        query.toLowerCase().includes('funded') ||
                        query.toLowerCase().includes('fully funded');
    
    if (isFreeSearch) {
      console.log('Free/funded search detected');
      conditions.push('(s.percentage_cover >= 75 OR LOWER(s.title) LIKE ? OR LOWER(s.description) LIKE ?)');
      params.push('%fully funded%', '%fully funded%', '%full tuition%', '%full tuition%');
    }
    
    // Basic text search for other terms
    const searchTerms = query.toLowerCase().split(' ').filter(term => 
      term.length > 2 && !['germany', 'free', 'funded', 'scholarship'].includes(term)
    );
    
    if (searchTerms.length > 0) {
      const searchConditions = searchTerms.map(() => 
        `(LOWER(s.title) LIKE ? OR LOWER(s.description) LIKE ? OR LOWER(c.country) LIKE ?)`
      ).join(' OR ');
      
      conditions.push(`(${searchConditions})`);
      searchTerms.forEach(term => {
        const searchTerm = `%${term}%`;
        params.push(searchTerm, searchTerm, searchTerm);
      });
    }
    
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    console.log('Search query conditions:', conditions);
    console.log('Search params:', params);
    
    let [results] = 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
      ${whereClause}
      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 
        s.percentage_cover DESC,
        COALESCE(s.amount_max, s.amount_min, 0) DESC
      LIMIT 25
    `, params);

    console.log('Search found results:', results?.length);

    if (!results || results.length === 0) {
      console.log('No results found, trying broader search...');
      // Try a broader search without specific country filter
      if (isGermanySearch) {
        const [broaderResults] = 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 LOWER(c.country) LIKE '%germany%' THEN 1 ELSE 0 END DESC,
            s.percentage_cover DESC
          LIMIT 25
        `);
        
        if (broaderResults && broaderResults.length > 0) {
          results = broaderResults;
          console.log('Broader search found results:', results.length);
        }
      }
      
      if (!results || results.length === 0) {
        return {
          data: [],
          insights: ['No scholarships found matching your search. Try broadening your search criteria.'],
          aiSummary: `No results found for "${query}"`
        };
      }
    }

    const enhancedResults = await Promise.all(
      results.map(async (scholarship: any) => {
        const matchScore = calculateBasicMatchScore(query, profile, scholarship);
        
        const qualifications = scholarship.qualifications ? 
          scholarship.qualifications.split(', ').filter((q: string) => q) : [];
        
        const scholarshipLink = scholarship.slug 
          ? `/scholarships/${scholarship.slug}`
          : `/scholarships/${scholarship.id}`;

        return {
          id: scholarship.id,
          title: scholarship.title,
          slug: scholarship.slug,
          country: scholarship.country_name || 'International',
          amount: calculateAmount(scholarship.amount_min, scholarship.amount_max),
          deadline: scholarship.deadline || 'Rolling Admission',
          matchScore: Math.round(matchScore),
          type: getScholarshipType(scholarship.percentage_cover),
          description: truncateDescription(scholarship.description || '', 150),
          eligibility: generateEnhancedEligibility(scholarship, profile),
          aiInsight: generateBasicAiInsight(scholarship, profile, matchScore),
          link: scholarshipLink,
          tags: generateScholarshipTags(scholarship, profile, qualifications),
          percentage_cover: scholarship.percentage_cover,
          required_cgpa: scholarship.required_cgpa?.toString(),
          ielts: scholarship.ielts,
          currency_symbol: scholarship.currency_symbol,
          qualifications: qualifications
        };
      })
    );

    // Generate insights
    const insights = [];
    const germanyScholarships = enhancedResults.filter(s => 
      s.country && s.country.toLowerCase().includes('germany')
    );
    const freeScholarships = enhancedResults.filter(s => 
      s.percentage_cover && s.percentage_cover >= 75
    );
    
    if (germanyScholarships.length > 0) {
      insights.push(`Found ${germanyScholarships.length} scholarships in Germany`);
    }
    
    if (freeScholarships.length > 0) {
      insights.push(`${freeScholarships.length} fully-funded opportunities available`);
    }
    
    if (enhancedResults.length > 0) {
      insights.unshift(`Found ${enhancedResults.length} matches for "${query}"`);
    }

    return {
      data: enhancedResults.sort((a, b) => b.matchScore - a.matchScore),
      insights: insights,
      aiSummary: `Search results for "${query}" - ${enhancedResults.length} scholarships found`
    };

  } catch (error) {
    console.error('Basic search error:', error);
    return {
      data: [],
      insights: ['Search encountered an error. Please try again.'],
      aiSummary: 'Search failed due to technical error.'
    };
  }
}

function calculateBasicMatchScore(query: string, profile: EnhancedProfile, scholarship: any): number {
  let score = 50;
  
  // Query match
  const scholarshipText = `${scholarship.title} ${scholarship.description}`.toLowerCase();
  const queryLower = query.toLowerCase();
  
  // Check for exact match
  if (scholarshipText.includes(queryLower)) {
    score += 30;
  } else if (query.split(' ').some(term => 
    term.length > 3 && scholarshipText.includes(term.toLowerCase()))) {
    score += 20;
  }
  
  // Check for Germany specifically
  if (query.toLowerCase().includes('germany')) {
    if (scholarship.country_name && scholarship.country_name.toLowerCase().includes('germany')) {
      score += 25;
    }
  }
  
  // Check for free/funded
  if ((query.toLowerCase().includes('free') || query.toLowerCase().includes('funded')) && 
      scholarship.percentage_cover && scholarship.percentage_cover >= 75) {
    score += 20;
  }
  
  // GPA consideration
  const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
  const requiredCGPA = parseFloat(scholarship.required_cgpa) || 0;
  
  if (requiredCGPA === 0) {
    score += 15;
  } else if (studentCGPA >= requiredCGPA) {
    score += 15;
  } else if (studentCGPA > 0) {
    score += 5;
  }
  
  return Math.max(40, Math.min(90, score));
}

function generateBasicAiInsight(scholarship: any, profile: EnhancedProfile, matchScore: number): string {
  const insights = [];
  
  const requiredCGPA = parseFloat(scholarship.required_cgpa) || 0;
  if (requiredCGPA === 0) {
    insights.push('No GPA requirement');
  } else if (requiredCGPA <= 2.5) {
    insights.push('Low GPA requirement');
  }
  
  if (scholarship.ielts === 0) {
    insights.push('No IELTS required');
  }
  
  if (scholarship.percentage_cover >= 75) {
    insights.push('High funding coverage');
  }
  
  if (scholarship.country_name && scholarship.country_name.toLowerCase().includes('germany')) {
    insights.push('Germany opportunity');
  }
  
  if (insights.length === 0) {
    return 'Review scholarship details for eligibility';
  }
  
  return insights.join(' • ');
}

function extractSearchParametersWithContext(query: string, profile?: EnhancedProfile): any {
  const params: any = {};
  const lowerQuery = query.toLowerCase();
  
  // Country detection
  const countriesList = [
    'germany', 'usa', 'united states', 'canada', 'uk', 'united kingdom', 'australia',
    'france', 'japan', 'singapore', 'china', 'uae', 'pakistan'
  ];
  
  for (const country of countriesList) {
    if (lowerQuery.includes(country)) {
      params.countries = [country];
      break;
    }
  }
  
  // Scholarship type detection
  if (lowerQuery.includes('fully funded') || lowerQuery.includes('full tuition') || lowerQuery.includes('free')) {
    params.scholarshipType = 'fully_funded';
  } else if (lowerQuery.includes('partial')) {
    params.scholarshipType = 'partial';
  }
  
  // Field of study detection
  const studyFields = [
    'computer science', 'engineering', 'business', 'medicine', 'arts', 
    'humanities', 'science', 'mathematics', 'architecture', 'design',
    'education', 'law', 'agriculture', 'data science', 'ai', 'artificial intelligence'
  ];
  
  for (const field of studyFields) {
    if (lowerQuery.includes(field)) {
      params.fieldOfStudy = field;
      break;
    }
  }
  
  return params;
}

// Helper Functions
function getDegreeKeywords(degreeLevel: string): string[] {
  const keywords: Record<string, string[]> = {
    'bachelors': ['bachelor', 'undergraduate', 'bsc', 'ba', 'b.a.', 'b.s.', 'undergrad'],
    'masters': ['master', 'graduate', 'msc', 'ma', 'mba', 'm.a.', 'm.s.', 'm.eng', 'postgraduate'],
    'phd': ['phd', 'doctorate', 'doctoral', 'd.phil', 'ph.d', 'doctor of philosophy']
  };
  return keywords[degreeLevel] || [degreeLevel];
}

function getRelatedFields(field: string): string[] {
  const relatedMap: Record<string, string[]> = {
    'engineering': ['technology', 'technical', 'engineering', 'mechanical', 'electrical', 'civil', 'construction'],
    'computer science': ['cs', 'software', 'programming', 'it', 'information technology', 'computing'],
    'business': ['management', 'administration', 'commerce', 'finance', 'marketing', 'economics'],
    'medicine': ['medical', 'health', 'healthcare', 'nursing', 'pharmacy', 'clinical']
  };
  return relatedMap[field.toLowerCase()] || [];
}

function getFallbackScholarships(profile: EnhancedProfile): Scholarship[] {
  return [{
    id: 999,
    title: 'General International Scholarship',
    country: 'Various',
    amount: 15000,
    deadline: '2024-12-31',
    matchScore: 50,
    type: 'partial',
    description: 'General scholarship opportunity for international students',
    eligibility: ['Open to all nationalities', 'Minimum academic standing'],
    aiInsight: 'Broad eligibility criteria make this accessible to most students',
    link: '#',
    tags: ['International', 'General']
  }];
}

function generateScholarshipTags(scholarship: any, profile: EnhancedProfile, qualifications: string[] = []): string[] {
  const tags: string[] = [];
  
  const percentageCover = scholarship?.percentage_cover || 0;
  if (percentageCover === 100) tags.push('Full Tuition');
  else if (percentageCover >= 75) tags.push('Fully Funded');
  else if (percentageCover >= 50) tags.push('Partial Funding');
  else if (percentageCover > 0) tags.push('Financial Aid');
  
  const amount = calculateAmount(scholarship?.amount_min, scholarship?.amount_max);
  if (amount > 40000) tags.push('High Value');
  else if (amount > 20000) tags.push('Generous');
  
  if (scholarship?.ielts === 0) tags.push('No IELTS');
  
  const requiredGPA = parseFloat(scholarship.required_cgpa) || 0;
  if (requiredGPA === 0) {
    tags.push('No GPA Req');
  } else if (requiredGPA <= 2.5) {
    tags.push('Low GPA Req');
  }
  
  // Add country tag
  if (scholarship?.country_name) {
    tags.push(scholarship.country_name);
  }
  
  // Add qualification tags (first 2)
  if (qualifications.length > 0) {
    tags.push(...qualifications.slice(0, 2).map(q => q.substring(0, 15)));
  }
  
  return tags.slice(0, 5);
}

function generateEnhancedEligibility(scholarship: any, profile: EnhancedProfile): string[] {
  const eligibility = [];
  
  if (scholarship?.required_cgpa) {
    const studentCGPA = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
    const requiredCGPA = parseFloat(scholarship.required_cgpa);
    eligibility.push(`GPA: ${requiredCGPA} (Yours: ${studentCGPA || 'N/A'})`);
  } else {
    eligibility.push('GPA: Not specified');
  }
  
  if (scholarship?.ielts === 1) {
    const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
    eligibility.push(`IELTS Required (Yours: ${languageScore || 'N/A'})`);
  } else if (scholarship?.ielts === 0) {
    eligibility.push('No IELTS Required');
  }
  
  if (scholarship?.percentage_cover) {
    eligibility.push(`${scholarship.percentage_cover}% Tuition Covered`);
  }
  
  // Add deadline if available
  if (scholarship?.deadline && scholarship.deadline !== 'Rolling Admission') {
    try {
      const deadline = new Date(scholarship.deadline);
      eligibility.push(`Deadline: ${deadline.toLocaleDateString()}`);
    } catch (e) {
      eligibility.push(`Deadline: ${scholarship.deadline}`);
    }
  }
  
  return eligibility.slice(0, 4);
}

// Utility functions
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) {
    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';
  if (percentage >= 25) return 'financial_aid';
  return 'variable';
}

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

// Enhanced profile analysis with DeepSeek
async function analyzeEnhancedProfileWithDeepSeek(profile: EnhancedProfile, connection: any): Promise<Analysis> {
  try {
    // First get some scholarship matches for context
    const matches = await findEnhancedScholarshipMatches(profile, connection, true);
    
    // Calculate basic scores
    const academicScore = calculateEnhancedAcademicScore(profile);
    const profileCompleteness = calculateProfileCompletenessScore(profile);
    const competitiveness = calculateCompetitivenessScore(profile);
    
    const overallScore = Math.round(
      (academicScore * 0.40) + 
      (profileCompleteness * 0.30) + 
      (competitiveness * 0.30)
    );
    
    const totalFunding = matches?.reduce((sum, s) => sum + (s?.amount || 0), 0) || 0;
    
    // Try to get AI analysis from DeepSeek
    let aiAnalysis = null;
    if (DEEPSEEK_API_KEY) {
      aiAnalysis = await getDeepSeekAnalysis(profile, matches);
    }
    
    // If AI analysis fails, use generated analysis
    if (!aiAnalysis) {
      aiAnalysis = generateComprehensiveAnalysis(profile, matches, academicScore, profileCompleteness, competitiveness);
    }
    
    return {
      overallScore,
      strengths: aiAnalysis.strengths,
      weaknesses: aiAnalysis.weaknesses,
      recommendations: aiAnalysis.recommendations,
      estimatedSuccess: calculateEstimatedSuccessRate(profile, overallScore, matches),
      totalMatches: matches.length,
      totalFunding: `$${totalFunding.toLocaleString()}`,
      profileStrength: {
        academic: academicScore,
        profileCompleteness: profileCompleteness,
        competitiveness: competitiveness,
        readiness: Math.round((academicScore + profileCompleteness + competitiveness) / 3)
      },
      riskFactors: generateRiskFactors(profile, academicScore, profileCompleteness),
      timelineRecommendations: generateTimelineRecommendations(profile),
      scholarshipCategories: estimateScholarshipCategories(profile, overallScore),
      matchBreakdown: aiAnalysis.matchBreakdown,
      aiInsights: aiAnalysis.aiInsights,
      competitiveAnalysis: aiAnalysis.competitiveAnalysis
    };

  } catch (error) {
    console.error('Enhanced analysis error:', error);
    return getBasicAnalysis(profile);
  }
}

// Calculate enhanced academic score
function calculateEnhancedAcademicScore(profile: EnhancedProfile): number {
  let score = 50;
  const cgpa = parseFloat(profile?.academic?.cgpa?.replace(/[^0-9.]/g, '') || '0');
  
  if (cgpa >= 3.8) score += 40;
  else if (cgpa >= 3.5) score += 30;
  else if (cgpa >= 3.0) score += 20;
  else if (cgpa >= 2.5) score += 10;
  
  const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
  if (languageScore >= 7.5) score += 20;
  else if (languageScore >= 7.0) score += 15;
  else if (languageScore >= 6.5) score += 10;
  
  // Bonus for research and publications
  if (profile?.academic?.researchExperience) score += 10;
  if (profile?.academic?.publications) score += 5;
  if (profile?.academic?.awards) score += 5;
  
  return Math.min(100, score);
}

// Calculate profile completeness score
function calculateProfileCompletenessScore(profile: EnhancedProfile): number {
  let filledFields = 0;
  let totalFields = 0;

  // Personal Info (5 fields)
  const personalFields = ['fullName', 'email', 'age', 'nationality', 'currentCountry'];
  totalFields += personalFields.length;
  personalFields.forEach(field => {
    if (profile?.personal?.[field as keyof PersonalInfo]?.toString()?.trim()) filledFields++;
  });

  // Academic Info (4 required fields)
  const academicFields = ['educationLevel', 'cgpa', 'fieldOfStudy', 'languageScore'];
  totalFields += academicFields.length;
  academicFields.forEach(field => {
    if (profile?.academic?.[field as keyof AcademicInfo]?.toString()?.trim()) filledFields++;
  });

  // Preferences (3 fields)
  const preferenceFields = ['countries', 'degreeLevel', 'fundingPriority'];
  totalFields += preferenceFields.length;
  preferenceFields.forEach(field => {
    const value = profile?.preferences?.[field as keyof Preferences];
    if (Array.isArray(value)) {
      if (value?.length > 0) filledFields++;
    } else if (value?.toString()?.trim() && value !== 'any') {
      filledFields++;
    }
  });

  return Math.round((filledFields / totalFields) * 100);
}

// Calculate competitiveness score
function calculateCompetitivenessScore(profile: EnhancedProfile): number {
  let score = 60;
  
  const completeness = calculateProfileCompletenessScore(profile);
  score += Math.min(20, completeness / 5);
  
  const academicScore = calculateEnhancedAcademicScore(profile);
  if (academicScore >= 75) score += 15;
  else if (academicScore >= 65) score += 10;
  
  if (profile?.academic?.researchExperience) score += 10;
  if (profile?.academic?.publications) score += 5;
  
  return Math.min(100, score);
}

// Get DeepSeek analysis
async function getDeepSeekAnalysis(profile: EnhancedProfile, matches: Scholarship[]): Promise<any> {
  try {
    const prompt = `As an expert scholarship advisor, analyze this student profile and provide detailed insights:

STUDENT PROFILE:
• Education Level: ${profile?.academic?.educationLevel || 'Not specified'}
• Field of Study: ${profile?.academic?.fieldOfStudy || 'Not specified'}
• GPA/CGPA: ${profile?.academic?.cgpa || 'Not specified'}
• Language Score: ${profile?.academic?.languageScore || 'Not specified'}
• Research Experience: ${profile?.academic?.researchExperience || 'Not specified'}
• Publications: ${profile?.academic?.publications || 'Not specified'}

PREFERENCES:
• Preferred Countries: ${profile?.preferences?.countries?.join(', ') || 'Not specified'}
• Degree Level: ${profile?.preferences?.degreeLevel || 'Not specified'}
• Funding Priority: ${profile?.preferences?.fundingPriority || 'any'}

SCHOLARSHIP MATCHES FOUND: ${matches.length}

Please provide a comprehensive analysis including:

1. KEY STRENGTHS (3-4 bullet points highlighting strongest aspects)
2. AREAS FOR IMPROVEMENT (3-4 specific areas that need work)
3. RECOMMENDATIONS (4-5 actionable steps with priority levels)
4. MATCH BREAKDOWN (scores out of 100 for Academic, Country, Funding, and Timeline match)
5. COMPETITIVE ANALYSIS (percentile and specific opportunities)
6. AI INSIGHTS (3-4 key observations)

Format the response as a JSON object with these keys: strengths, weaknesses, recommendations, matchBreakdown, competitiveAnalysis, 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 with 10+ years of experience helping students secure funding. Provide detailed, actionable advice in JSON format.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        max_tokens: 1000,
        temperature: 0.7
      })
    });
    
    const data = await response.json();
    const content = data?.choices?.[0]?.message?.content || '';
    
    try {
      const cleanContent = content.replace(/```json\n?|\n?```/g, '').trim();
      const parsed = JSON.parse(cleanContent);
      return parsed;
    } catch (parseError) {
      console.error('Failed to parse DeepSeek response:', parseError, 'Content:', content);
      return generateComprehensiveAnalysis(profile, matches, 
        calculateEnhancedAcademicScore(profile), 
        calculateProfileCompletenessScore(profile),
        calculateCompetitivenessScore(profile)
      );
    }
    
  } catch (error) {
    console.error('DeepSeek API error:', error);
    return null;
  }
}

// Generate comprehensive analysis
function generateComprehensiveAnalysis(profile: EnhancedProfile, matches: Scholarship[], academicScore: number, completeness: number, competitiveness: number): any {
  const strengths = [];
  const weaknesses = [];
  const recommendations = [];
  
  // Strengths
  if (academicScore >= 80) {
    strengths.push('Excellent academic performance with strong GPA');
    strengths.push('Competitive profile for merit-based scholarships');
  } else if (academicScore >= 70) {
    strengths.push('Good academic record meeting most requirements');
    strengths.push('Solid foundation for scholarship applications');
  }
  
  const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
  if (languageScore >= 7.5) {
    strengths.push('Strong language proficiency for international programs');
  } else if (languageScore >= 7.0) {
    strengths.push('Adequate language scores for most scholarships');
  }
  
  if (profile?.academic?.researchExperience) {
    strengths.push('Research experience enhances eligibility for academic scholarships');
  }
  
  if (profile?.preferences?.countries?.length > 0) {
    strengths.push('Clear country preferences enable targeted applications');
  }
  
  // Weaknesses
  if (academicScore < 70) {
    weaknesses.push('Academic scores could be improved for competitive scholarships');
  }
  
  if (languageScore < 6.5) {
    weaknesses.push('Language proficiency below optimal level for many international scholarships');
  }
  
  if (!profile?.academic?.researchExperience && (profile?.preferences?.degreeLevel === 'masters' || profile?.preferences?.degreeLevel === 'phd')) {
    weaknesses.push('Research experience recommended for graduate-level scholarships');
  }
  
  if (profile?.preferences?.countries?.length === 0) {
    weaknesses.push('No country preferences specified, limiting targeted strategy');
  }
  
  // Recommendations
  recommendations.push('Complete profile to 100% for optimal matching (High Priority)');
  recommendations.push('Prepare strong, personalized letters of recommendation (High Priority)');
  recommendations.push('Tailor statement of purpose for each scholarship (Medium Priority)');
  
  if (languageScore < 7.0) {
    recommendations.push('Consider retaking language tests to achieve 7.0+ scores (Medium Priority)');
  }
  
  if (!profile?.academic?.researchExperience) {
    recommendations.push('Gain research experience through internships or projects (Medium Priority)');
  }
  
  // Match breakdown
  const matchBreakdown = {
    academicMatch: academicScore,
    countryMatch: calculateCountryMatch(profile, matches),
    fundingMatch: calculateFundingMatch(profile, matches),
    timelineMatch: 85
  };
  
  // Competitive analysis
  const competitiveAnalysis = {
    percentile: calculatePercentile(academicScore),
    strengths: ['Academic foundation', 'Clear goals', 'International perspective'],
    opportunities: ['Research publications', 'Leadership roles', 'Community service']
  };
  
  // AI insights
  const aiInsights = [];
  if (matches.length > 0) {
    const highMatches = matches.filter(m => m.matchScore >= 80).length;
    aiInsights.push(`Found ${matches.length} total matches with ${highMatches} high-quality opportunities`);
    aiInsights.push(`Total available funding: $${matches.reduce((sum, m) => sum + m.amount, 0).toLocaleString()}`);
  }
  
  if (completeness < 100) {
    aiInsights.push(`Complete your profile to unlock ${Math.round((100 - completeness) * 0.8)}% more accurate matches`);
  }
  
  return {
    strengths: strengths.length > 0 ? strengths : ['Solid foundation for scholarship applications'],
    weaknesses: weaknesses.length > 0 ? weaknesses : ['Consider additional documentation to strengthen application'],
    recommendations: recommendations,
    matchBreakdown: matchBreakdown,
    competitiveAnalysis: competitiveAnalysis,
    aiInsights: aiInsights.length > 0 ? aiInsights : ['Good starting point for scholarship applications']
  };
}

// Calculate country match percentage
function calculateCountryMatch(profile: EnhancedProfile, matches: Scholarship[]): number {
  const preferredCountries = profile?.preferences?.countries || [];
  if (preferredCountries.length === 0 || matches.length === 0) return 70;
  
  const countryMatches = matches.filter(s => 
    preferredCountries.some(country => s?.country?.toLowerCase().includes(country?.toLowerCase()))
  ).length;
  
  return Math.min(100, Math.round((countryMatches / matches.length) * 100));
}

// Calculate funding match percentage
function calculateFundingMatch(profile: EnhancedProfile, matches: Scholarship[]): number {
  const fundingPriority = profile?.preferences?.fundingPriority;
  if (fundingPriority === 'any' || matches.length === 0) return 80;
  
  const fundingMatches = matches.filter(s => {
    if (fundingPriority === 'full') return s?.type === 'fully_funded' || (s?.percentage_cover || 0) >= 75;
    if (fundingPriority === 'partial') return s?.type === 'partial' || ((s?.percentage_cover || 0) >= 25 && (s?.percentage_cover || 0) < 75);
    return true;
  }).length;
  
  return Math.min(100, Math.round((fundingMatches / matches.length) * 100));
}

// Calculate percentile
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;
}

// Calculate estimated success rate
function calculateEstimatedSuccessRate(profile: EnhancedProfile, overallScore: number, matches: Scholarship[]): number {
  let successRate = overallScore * 0.7;
  
  const highMatches = matches.filter(m => m.matchScore >= 80).length;
  successRate += Math.min(20, highMatches * 2);
  
  const completeness = calculateProfileCompletenessScore(profile);
  successRate += Math.min(10, completeness / 10);
  
  return Math.min(95, Math.max(30, Math.round(successRate)));
}

// Generate risk factors
function generateRiskFactors(profile: EnhancedProfile, academicScore: number, profileProgress: number): {
  factor: string;
  likelihood: 'high' | 'medium' | 'low';
  impact: 'high' | 'medium' | 'low';
  mitigation: string;
}[] {
  const risks = [];
  
  if (academicScore < 65) {
    risks.push({
      factor: 'Academic profile below average for competitive scholarships',
      likelihood: 'high',
      impact: 'high',
      mitigation: 'Focus on scholarships with lower GPA requirements or improve academic performance'
    });
  }
  
  const languageScore = parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0');
  if (!profile?.academic?.languageScore || languageScore < 6.5) {
    risks.push({
      factor: 'Missing or low language proficiency scores',
      likelihood: 'medium',
      impact: 'high',
      mitigation: 'Retake language tests or target scholarships without language requirements'
    });
  }
  
  if (profileProgress < 60) {
    risks.push({
      factor: 'Incomplete profile affecting match accuracy',
      likelihood: 'high',
      impact: 'medium',
      mitigation: 'Complete all profile sections for better matching'
    });
  }
  
  return risks;
}

// Generate timeline recommendations
function generateTimelineRecommendations(profile: EnhancedProfile): string[] {
  const recommendations = [];
  
  recommendations.push('Start applications 3-4 months before deadlines');
  recommendations.push('Request recommendation letters at least 2 months in advance');
  recommendations.push('Prepare all documents (transcripts, certificates) in advance');
  
  if (parseFloat(profile?.academic?.languageScore?.replace(/[^0-9.]/g, '') || '0') < 7.0) {
    recommendations.push('Schedule language test retakes 3 months before application deadlines');
  }
  
  return recommendations.slice(0, 3);
}

// Estimate scholarship categories
function estimateScholarshipCategories(profile: EnhancedProfile, overallScore: number): { highMatch: number; mediumMatch: number; lowMatch: number } {
  if (overallScore >= 85) {
    return { highMatch: 60, mediumMatch: 30, lowMatch: 10 };
  } else if (overallScore >= 75) {
    return { highMatch: 40, mediumMatch: 40, lowMatch: 20 };
  } else if (overallScore >= 65) {
    return { highMatch: 25, mediumMatch: 45, lowMatch: 30 };
  } else if (overallScore >= 55) {
    return { highMatch: 15, mediumMatch: 35, lowMatch: 50 };
  } else {
    return { highMatch: 10, mediumMatch: 30, lowMatch: 60 };
  }
}

// Basic analysis fallback
function getBasicAnalysis(profile: EnhancedProfile): Analysis {
  const completeness = calculateProfileCompletenessScore(profile);
  const academicScore = calculateEnhancedAcademicScore(profile);
  const competitiveness = calculateCompetitivenessScore(profile);
  
  return {
    overallScore: Math.round((academicScore + completeness + competitiveness) / 3),
    strengths: ['Profile information provided', 'Basic requirements met'],
    weaknesses: ['Complete all required fields for better analysis'],
    recommendations: ['Fill in all required fields', 'Add more details to academic section'],
    estimatedSuccess: Math.min(60, completeness),
    totalMatches: 0,
    totalFunding: '$0',
    profileStrength: {
      academic: academicScore,
      profileCompleteness: completeness,
      competitiveness: competitiveness,
      readiness: Math.round((academicScore + completeness + competitiveness) / 3)
    },
    riskFactors: [{
      factor: 'Incomplete profile may limit opportunities',
      likelihood: 'high',
      impact: 'medium',
      mitigation: 'Complete all profile sections'
    }],
    timelineRecommendations: ['Complete profile first', 'Start applications early'],
    scholarshipCategories: {
      highMatch: Math.round(completeness * 0.3),
      mediumMatch: Math.round(completeness * 0.4),
      lowMatch: Math.round(completeness * 0.3)
    }
  };
}

export async function GET() {
  return NextResponse.json({
    success: true,
    message: 'Intelligent Scholarship Match API',
    endpoints: {
      POST: {
        '/api/scholarships/match': 'Find intelligent scholarship matches with GPA-aware scoring'
      }
    },
    features: ['GPA-aware matching', 'Context-aware search', 'Qualifications integration', 'DeepSeek AI insights']
  });
}