// src/app/api/frontend/ai-embassy-interview-predictor/route.ts
import { NextRequest, NextResponse } from 'next/server';

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

interface InterviewRequest {
  country: string;
  course: string;
  degreeLevel: string;
  universityType: string;
  sponsorType: string;
  studyGap: string;
  previousRefusals: boolean;
  languageProof: string;
  ieltsScore?: number;
  age?: number;
  workExperience?: number;
}

interface Question {
  question: string;
  category: 'study_intent' | 'financial' | 'return_intent' | 'background';
  riskLevel: 'low' | 'medium' | 'high';
  intent: string;
  sampleAnswer: string;
  officerIntent: string;
  commonMistakes: string[];
  likelyFollowUps: string[];
}

interface PredictionResponse {
  interviewReadinessScore: number;
  confidence: number;
  riskLevel: 'low' | 'medium' | 'high';
  topQuestions: Question[];
  weakAreas: {
    area: string;
    severity: 'low' | 'medium' | 'high';
    improvement: string;
  }[];
  countryInsights: {
    focus: string[];
    officerMindset: string[];
    avoid: string[];
  };
  generatedAt: string;
  disclaimer: string;
  limited?: boolean;
  totalQuestions?: number;
  unlockMessage?: string;
}

// Simple auth check
async function checkAuth(request: NextRequest): Promise<{ 
  id?: string; 
  email?: string;
  role?: string;
  isFullUser: boolean;
  isValid: boolean;
}> {
  try {
    const token = request.cookies.get("university-token")?.value || null;
    
    if (!token) {
      return { isValid: false, isFullUser: false };
    }
    
    return {
      id: 'user-' + Math.random().toString(36).substr(2, 9),
      email: 'user@example.com',
      role: 'student',
      isFullUser: token.length > 10,
      isValid: true
    };
    
  } catch (error) {
    return { isValid: false, isFullUser: false };
  }
}

// Smart risk calculation with personalized insights
function calculateRiskProfile(data: InterviewRequest): {
  score: number;
  risk: 'low' | 'medium' | 'high';
  weakAreas: any[];
  personalizedRiskFactors: string[];
} {
  let score = 75;
  const weakAreas = [];
  const personalizedRiskFactors = [];

  // Previous refusals
  if (data.previousRefusals) {
    score -= 20;
    weakAreas.push({
      area: 'Previous Visa Refusal',
      severity: 'high' as const,
      improvement: 'Prepare detailed explanation letter with new supporting documents specifically addressing the refusal reasons'
    });
    personalizedRiskFactors.push('Previous visa refusal requires strong justification');
  }

  // Study gap analysis
  const gapMatch = data.studyGap.match(/\d+/);
  const gapYears = gapMatch ? parseInt(gapMatch[0]) : 0;
  if (gapYears >= 1) {
    const penalty = gapYears >= 6 ? 20 : gapYears >= 4 ? 15 : gapYears >= 2 ? 10 : 5;
    score -= penalty;
    
    const severity: 'low' | 'medium' | 'high' =
  gapYears >= 6 ? 'high' : gapYears >= 3 ? 'medium' : 'low';

    weakAreas.push({
  area: `${gapYears} year${gapYears > 1 ? 's' : ''} Study Gap`,
  severity, // ✅ NO "as const"
  improvement: `Document all activities during gap: work experience (${data.workExperience || 0} years), certifications, skills development. Show progression logic.`
});

    personalizedRiskFactors.push(`${gapYears}-year study gap requires detailed justification`);
  }

  // Sponsor risk analysis
  const sponsorRiskMapping: Record<string, {score: number, risk: string, note: string}> = {
    'Self-funded': { score: +5, risk: 'low', note: 'Strong financial position' },
    'Parents': { score: 0, risk: 'low', note: 'Family sponsorship - prepare relationship proof' },
    'Scholarship': { score: +3, risk: 'low', note: 'Merit-based funding - show achievement proof' },
    'Relative': { score: -12, risk: 'high', note: 'Distant relative sponsorship - strong relationship proof needed' },
    'Education Loan': { score: -8, risk: 'medium', note: 'Loan repayment concerns - show career viability' },
    'Employer': { score: -5, risk: 'medium', note: 'Employer sponsorship - return obligation proof needed' }
  };

  const sponsor = sponsorRiskMapping[data.sponsorType] || { score: -10, risk: 'high', note: 'Unclear sponsorship' };
  score += sponsor.score;
  
  if (sponsor.risk !== 'low') {
    weakAreas.push({
      area: `${data.sponsorType} Sponsorship`,
      severity: sponsor.risk as any,
      improvement: `Prepare detailed ${data.sponsorType.toLowerCase()} relationship proof, income documents, tax returns, and clear motivation letter explaining the sponsorship`
    });
    personalizedRiskFactors.push(`${data.sponsorType} sponsorship requires extra documentation`);
  }

  // Age and experience analysis
  if (data.age) {
    if (data.age > 35) {
      score -= 10;
      personalizedRiskFactors.push(`Age ${data.age} may raise questions about career timing`);
    } else if (data.age < 20) {
      score -= 3;
      personalizedRiskFactors.push(`Young age (${data.age}) requires strong academic preparation proof`);
    }
  }

  // Language proficiency
  if (data.ieltsScore) {
    if (data.ieltsScore < 6.0) {
      score -= 12;
      weakAreas.push({
        area: `Low IELTS Score (${data.ieltsScore})`,
        severity: 'high' as const,
        improvement: 'Prepare English improvement plan, consider taking additional language courses, show university conditional acceptance if applicable'
      });
      personalizedRiskFactors.push(`Low IELTS score ${data.ieltsScore} requires explanation`);
    } else if (data.ieltsScore >= 7.5) {
      score += 5;
      personalizedRiskFactors.push(`Strong IELTS score ${data.ieltsScore} is an advantage`);
    }
  } else if (data.languageProof === 'No English Test') {
    score -= 8;
    personalizedRiskFactors.push('No English test may raise concerns');
  }

  // Work experience bonus/penalty
  if (data.workExperience) {
    if (data.workExperience >= 5 && data.age && data.age > 28) {
      score -= 5; // Too much experience may raise career change concerns
      personalizedRiskFactors.push(`${data.workExperience} years work experience at age ${data.age} requires clear career progression logic`);
    } else if (data.workExperience >= 2) {
      score += Math.min(data.workExperience * 1.5, 10);
      personalizedRiskFactors.push(`${data.workExperience} years work experience is valuable for application`);
    }
  }

  // University type risk
  const universityRisk = {
    'Public University (High Ranking)': { bonus: +5 },
    'Public University (Mid Ranking)': { bonus: 0 },
    'Private University': { bonus: -3 },
    'Community College': { bonus: -8 },
    'Vocational Institute': { bonus: -10 }
  };
  
  const uniBonus = (universityRisk as any)[data.universityType]?.bonus || 0;
  score += uniBonus;
  if (uniBonus < 0) {
    personalizedRiskFactors.push(`${data.universityType} may raise questions about academic quality`);
  }

  const risk = score >= 75 ? 'low' : score >= 60 ? 'medium' : 'high';
  
  return {
    score: Math.max(30, Math.min(95, score)),
    risk,
    weakAreas,
    personalizedRiskFactors
  };
}

// Generate truly personalized questions using DeepSeek API
async function generatePersonalizedQuestionsWithDeepSeek(
  data: InterviewRequest, 
  riskProfile: any, 
  questionCount: number
): Promise<Question[]> {
  if (!DEEPSEEK_API_KEY) {
    throw new Error('DeepSeek API key not configured');
  }

  try {
    // Create a highly personalized prompt based on ALL user data
    const personalizedPrompt = `ANALYZE THIS STUDENT'S SPECIFIC VISA PROFILE AND GENERATE PERSONALIZED EMBASSY INTERVIEW QUESTIONS:

STUDENT'S UNIQUE PROFILE:
1. APPLICANT PROFILE:
   - Destination: ${data.country} Embassy
   - Course: ${data.course}
   - Degree Level: ${data.degreeLevel}
   - University: ${data.universityType}
   - Age: ${data.age || 'Not specified'}
   - Work Experience: ${data.workExperience || 0} years

2. RISK FACTORS TO FOCUS ON:
   - Sponsor: ${data.sponsorType} ${data.sponsorType === 'Relative' ? '(HIGH RISK - need strong relationship proof)' : ''}
   - Study Gap: ${data.studyGap} ${parseInt(data.studyGap) > 2 ? '(MODERATE-HIGH RISK - needs detailed gap explanation)' : ''}
   - Previous Refusals: ${data.previousRefusals ? 'YES (EXTREME RISK - must address previous refusal specifically)' : 'No'}
   - Language Proof: ${data.languageProof} ${data.ieltsScore ? `(Score: ${data.ieltsScore}/9)` : ''}
   - Overall Risk Level: ${riskProfile.risk.toUpperCase()}

3. COUNTRY-SPECIFIC CONCERNS:
   - ${data.country} embassy is particularly sensitive about: ${getCountrySpecificConcerns(data.country)}

4. PERSONALIZED RISK POINTS FROM ANALYSIS:
   ${riskProfile.personalizedRiskFactors.map(factor => `• ${factor}`).join('\n   ')}

GENERATE ${questionCount} HIGHLY PERSONALIZED, CONTEXT-SPECIFIC INTERVIEW QUESTIONS THAT:
1. DIRECTLY ADDRESS THIS SPECIFIC STUDENT'S PROFILE
2. FOCUS ON THEIR UNIQUE RISK FACTORS (${riskProfile.personalizedRiskFactors.join(', ')})
3. FOLLOW ${data.country}'S VISA OFFICER PSYCHOLOGY
4. INCLUDE TRICK QUESTIONS SPECIFIC TO THEIR SITUATION
5. VARY IN CATEGORY: study_intent, financial, return_intent, background

MAKE EACH QUESTION:
• SPECIFIC to their ${data.course}, ${data.universityType}, ${data.sponsorType} sponsorship
• REALISTIC - exactly what a ${data.country} visa officer would ask
• UNIQUE - not generic template questions
• RISK-ADJUSTED - focus on their specific weak areas

For EACH question, provide:
{
  "question": "Highly specific, personalized question addressing their unique situation",
  "category": "study_intent/financial/return_intent/background",
  "riskLevel": "low/medium/high (based on their specific risk)",
  "intent": "Why officer asks THIS student THIS question",
  "sampleAnswer": "Personalized answer addressing THEIR specific situation",
  "officerIntent": "Hidden agenda - what they're REALLY checking for THIS student",
  "commonMistakes": ["Mistakes THIS student might make"],
  "likelyFollowUps": ["Specific follow-ups for THIS case"]
}

EXAMPLE OF PERSONALIZED QUESTION (not to use, just style):
For a 35-year-old with 10 years work experience going for MBA: 
"At age 35 with established career, why pursue an MBA now instead of continuing professional advancement?"

Return ONLY JSON array with ${questionCount} personalized questions.`;

    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 ${data.country} visa officer with 20+ years experience. You analyze EACH student's UNIQUE profile and create SPECIFIC interview questions targeting THEIR personal risk factors. You NEVER use generic templates - every question is personalized based on their age, course, gap, sponsor, work experience, and country. Return ONLY JSON arrays.` 
          },
          { 
            role: 'user', 
            content: personalizedPrompt 
          }
        ],
        temperature: 0.8, // Higher temperature for more creative, personalized questions
        max_tokens: 4000,
        response_format: { type: 'json_object' }
      }),
      signal: AbortSignal.timeout(20000)
    });

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

    const result = await response.json();
    const content = result.choices[0]?.message?.content;
    
    if (!content) {
      throw new Error('Empty response from AI');
    }

    const parsed = JSON.parse(content);
    
    // Extract questions from various possible response formats
    let questions: Question[] = [];
    const possibleQuestionKeys = ['questions', 'topQuestions', 'data', 'interviewQuestions', 'predictedQuestions'];
    
    for (const key of possibleQuestionKeys) {
      if (parsed[key] && Array.isArray(parsed[key])) {
        questions = parsed[key];
        break;
      }
    }
    
    // If no array found, check if the entire response is an array
    if (questions.length === 0 && Array.isArray(parsed)) {
      questions = parsed;
    }
    
    // If still no questions, look for any array in the object
    if (questions.length === 0) {
      for (const value of Object.values(parsed)) {
        if (Array.isArray(value) && value.length > 0 && typeof value[0] === 'object') {
          questions = value;
          break;
        }
      }
    }

    // If AI failed to generate questions, throw error to trigger fallback
    if (questions.length === 0) {
      throw new Error('AI generated empty question list');
    }

    // Ensure we have exactly questionCount questions
    if (questions.length > questionCount) {
      questions = questions.slice(0, questionCount);
    } else if (questions.length < questionCount) {
      // Generate additional personalized questions locally
      const additionalCount = questionCount - questions.length;
      const additionalQuestions = generateAdditionalPersonalizedQuestions(data, additionalCount);
      questions = [...questions, ...additionalQuestions];
    }

    return questions;

  } catch (error) {
    console.error('DeepSeek API personalized generation failed:', error);
    throw error;
  }
}

// Helper function for country-specific concerns
function getCountrySpecificConcerns(country: string): string {
  const concerns: Record<string, string> = {
    'UK': 'academic progression logic, course relevance to previous studies, concrete career plans in home country',
    'USA': 'non-immigrant intent, strong family/business ties to home country, career prospects back home',
    'Canada': 'Genuine Student Intent (GSI), financial capacity proof, strong post-study return plans',
    'Australia': 'Genuine Temporary Entrant (GTE), course value for home country, sustainable finances',
    'Germany': 'academic preparation level, language proficiency, precise study planning',
    'Italy': 'financial capacity proof, study motivation clarity, Italian language basics if applicable',
    'default': 'genuine study intent, financial sustainability, strong return motivation'
  };
  
  return concerns[country] || concerns.default;
}

// Helper functions for personalized content
function getCareerPosition(age: number, experience?: number): string {
  if (age > 35) return 'senior manager/director';
  if (age > 28) return 'mid-level manager';
  return 'junior professional';
}

function getIndustryFromCourse(course: string): string {
  if (course.includes('Computer') || course.includes('IT') || course.includes('Software')) return 'technology sector';
  if (course.includes('Business') || course.includes('MBA') || course.includes('Management')) return 'business management';
  if (course.includes('Engineering')) return 'engineering industry';
  if (course.includes('Finance') || course.includes('Accounting')) return 'financial services';
  return 'relevant industry';
}

function getEmergingTech(course: string): string {
  if (course.includes('Computer') || course.includes('AI') || course.includes('Data')) return 'AI, machine learning, and cloud computing';
  if (course.includes('Business') || course.includes('MBA')) return 'digital transformation and analytics';
  if (course.includes('Engineering')) return 'sustainable technologies and automation';
  return 'emerging technologies in the field';
}

function getPracticalGoal(course: string): string {
  if (course.includes('Community College') || course.includes('Vocational')) return 'immediate employment in technical roles';
  return 'practical skill application in industry';
}

function getWorkSkills(experience?: number): string {
  if (!experience || experience < 2) return 'basic professional skills';
  if (experience < 5) return 'project management and team collaboration';
  return 'leadership, strategic planning, and complex problem-solving';
}

function getGapActivities(gap: string): string {
  const years = parseInt(gap) || 0;
  if (years === 0) return 'continuous learning';
  if (years <= 2) return 'online courses and professional development';
  return 'extensive self-study, certifications, and practical projects';
}

function getHomeCountryCompanies(): string {
  return 'companies like [insert 2-3 relevant companies in home country]';
}

// New helper functions for personalized question generation
function getTuitionEstimate(country: string): string {
  const estimates: Record<string, string> = {
    'UK': '£15,000-£25,000 annually',
    'USA': '$25,000-$50,000 annually',
    'Canada': 'CAD 20,000-35,000 annually',
    'Australia': 'AUD 25,000-45,000 annually',
    'Germany': '€10,000-€20,000 annually',
    'Italy': '€8,000-€15,000 annually',
    'default': 'the estimated tuition costs'
  };
  return estimates[country] || estimates.default;
}

function getBufferPercentage(): string {
  return '20%';
}

function getInternationalEdge(course: string): string {
  if (course.includes('International') || course.includes('Global')) {
    return 'global business practices and cross-cultural management';
  }
  return 'international standards and best practices';
}

function getBackgroundSummary(data: InterviewRequest): string {
  const parts = [];
  if (data.workExperience && data.workExperience > 0) {
    parts.push(`${data.workExperience} years in ${getIndustryFromCourse(data.course)}`);
  }
  if (parseInt(data.studyGap) > 0) {
    parts.push(`${data.studyGap} gap with ${getGapActivities(data.studyGap)}`);
  }
  if (data.age && data.age > 25) {
    parts.push(`mature student perspective`);
  }
  return parts.length > 0 ? parts.join(', ') : 'academic background';
}

function getRelevantExperience(data: InterviewRequest): string {
  if (data.workExperience && data.workExperience > 0) {
    return `${getWorkSkills(data.workExperience)} in ${getIndustryFromCourse(data.course)}`;
  }
  if (parseInt(data.studyGap) > 0) {
    return `self-directed learning during ${data.studyGap} gap`;
  }
  return 'academic studies and research';
}

function getLearnedSkills(data: InterviewRequest): string {
  if (data.workExperience && data.workExperience >= 3) {
    return 'professional discipline, time management, and practical problem-solving';
  }
  if (data.workExperience && data.workExperience > 0) {
    return 'team collaboration and project coordination';
  }
  return 'analytical thinking and research skills';
}

function getCourseApplication(course: string): string {
  return `advanced ${course.split(' in ')[0]?.toLowerCase() || 'subject'} concepts`;
}

function getPreparationSteps(data: InterviewRequest): string {
  const steps = [];
  if (parseInt(data.studyGap) > 0) {
    steps.push('completing relevant online courses');
  }
  if (data.ieltsScore && data.ieltsScore < 7) {
    steps.push('intensive English language preparation');
  }
  steps.push('researching university curriculum and connecting with current students');
  steps.push('reviewing foundational academic materials');
  return steps.join(', ');
}

function getIndustryField(course: string): string {
  if (course.includes('Computer') || course.includes('IT')) return 'technology';
  if (course.includes('Business') || course.includes('MBA')) return 'business management';
  if (course.includes('Engineering')) return 'engineering';
  if (course.includes('Finance')) return 'finance';
  if (course.includes('Health') || course.includes('Medical')) return 'healthcare';
  return 'your field';
}

function getLocalProblems(course: string): string {
  if (course.includes('Computer')) return 'digital transformation and tech talent shortage';
  if (course.includes('Business')) return 'management expertise gap and global competition';
  if (course.includes('Engineering')) return 'infrastructure development and sustainable solutions';
  if (course.includes('Finance')) return 'financial inclusion and regulatory frameworks';
  return 'specific industry challenges requiring advanced expertise';
}

function getCountryExpertise(country: string, course: string): string {
  const expertise: Record<string, string> = {
    'UK': 'academic excellence and research innovation',
    'USA': 'cutting-edge technology and entrepreneurial education',
    'Canada': 'practical, industry-focused training',
    'Australia': 'innovative teaching methods and research',
    'Germany': 'technical precision and engineering excellence',
    'Italy': 'specialized design and creative industries'
  };
  
  const baseExpertise = expertise[country] || 'advanced educational approaches';
  
  if (course.includes('Art') || course.includes('Design')) {
    return `${baseExpertise} in creative fields`;
  }
  if (course.includes('Technology') || course.includes('Engineering')) {
    return `${baseExpertise} in technical fields`;
  }
  
  return baseExpertise;
}

function getProgramFeatures(course: string): string {
  if (course.includes('MBA') || course.includes('Management')) {
    return 'case-study based, industry-integrated learning';
  }
  if (course.includes('Research') || course.includes('PhD')) {
    return 'research-intensive, mentorship-focused';
  }
  return 'practical, skill-based curriculum';
}

function getUniqueFeature(course: string, universityType: string): string {
  if (universityType.includes('High Ranking')) return 'cutting-edge research facilities and industry partnerships';
  if (universityType.includes('Community College')) return 'hands-on practical training and job placement programs';
  return 'specialized curriculum and expert faculty';
}

function getCourseGoal(course: string): string {
  if (course.includes('MBA')) return 'strategic leadership and global business management';
  if (course.includes('Computer')) return 'software architecture and emerging technology implementation';
  if (course.includes('Engineering')) return 'innovative problem-solving and sustainable design';
  return 'advanced expertise and professional advancement';
}

function getHomeCountry(): string {
  return 'your home country';
}

function getTargetRoles(course: string): string {
  if (course.includes('MBA')) return 'Strategy Consultant or Business Development Manager';
  if (course.includes('Computer')) return 'Software Architect or Tech Lead';
  return 'specialist or manager roles';
}

function getTargetCompanies(course: string): string {
  if (course.includes('Computer')) return 'tech companies and startups';
  if (course.includes('Business')) return 'consulting firms and multinational corporations';
  if (course.includes('Engineering')) return 'engineering firms and infrastructure companies';
  return 'leading organizations in my home country';
}

// Risk-based question helpers
function getIndustryTrend(course: string): string {
  if (course.includes('AI') || course.includes('Machine Learning')) {
    return 'the rapid evolution of artificial intelligence and automation';
  }
  if (course.includes('Data')) {
    return 'the explosion of big data and analytics requirements';
  }
  if (course.includes('Sustainability') || course.includes('Environmental')) {
    return 'the urgent need for sustainable solutions';
  }
  return 'significant technological and methodological advancements';
}

function getSpecificSkills(course: string): string {
  if (course.includes('Computer')) return 'programming, system design, and algorithm development';
  if (course.includes('Business')) return 'strategic planning, financial analysis, and leadership';
  if (course.includes('Engineering')) return 'design principles, project management, and technical analysis';
  return 'specialized knowledge and practical skills';
}

function getGapObservation(data: InterviewRequest): string {
  if (parseInt(data.studyGap) >= 3) {
    return 'how quickly theoretical knowledge becomes outdated without formal education';
  }
  return 'the gap between self-taught skills and formally recognized qualifications';
}

function getRelativeRelation(): string {
  return 'close relative who believes in educational investment';
}

function getPersonalAchievement(): string {
  return 'academic and professional accomplishments';
}

function getFamilyBenefit(): string {
  return 'contribute significantly to our family\'s future';
}

function getFamilyValues(): string {
  return 'education, mutual support, and long-term growth';
}

function getRepaymentCommitment(): string {
  return 'apply my education to create opportunities that benefit our entire family';
}

function getRefusalLesson(): string {
  return 'providing comprehensive, well-documented evidence';
}

function getImprovementActions(): string {
  return 'strengthened my financial documentation, obtained stronger recommendation letters, and clarified my career goals';
}

function getNewEvidence(): string {
  return 'additional work experience, updated financial statements, and specific career opportunity evidence';
}

function getPreviousConcern(): string {
  return 'my genuine study intent and financial capability';
}

function getLanguagePreparation(): string {
  return 'enrolled in intensive English courses and practiced daily with native speakers';
}

function getUniversityLanguageSupport(): string {
  return 'utilize the university\'s writing center and language support services';
}

function getLanguageStrength(): string {
  return 'reading comprehension and technical vocabulary';
}

function getAcademicCompensation(): string {
  return 'academic success through diligent preparation and seeking help when needed';
}

// Generate additional personalized questions based on specific data
function generateAdditionalPersonalizedQuestions(data: InterviewRequest, count: number): Question[] {
  const questions: Question[] = [];
  const usedQuestions = new Set<string>();
  
  // Helper to get personalized question variations
  // Replace the generateVariant function with this corrected version:
// Replace the generateVariant function with this corrected version:
const generateVariant = (index: number): Question => {
  // Determine risk levels based on data
  const financialRiskLevel: 'low' | 'medium' | 'high' = data.sponsorType === 'Relative' ? 'high' : 'medium';
  const backgroundRiskLevel: 'low' | 'medium' | 'high' = data.age && data.age > 30 ? 'medium' : 'low';
  
  const variants: Question[] = [
    // Study Intent Questions
    {
      question: `Why specifically did you choose ${data.course} at ${data.universityType} over similar programs in your home country or other destinations?`,
      category: 'study_intent',
      riskLevel: 'medium',
      intent: 'Test genuine university and course selection process',
      sampleAnswer: `${data.universityType} offers unique ${getUniqueFeature(data.course, data.universityType)} which aligns with my goal of ${getCourseGoal(data.course)}. Their focus on ${data.course.split(' in ')[1] || data.course} is unmatched in my home country.`,
      officerIntent: 'Verify student did proper research and isn\'t just choosing randomly',
      commonMistakes: ['"Better education" without specifics', 'Rankings-only reasoning', 'No comparison to home country options'],
      likelyFollowUps: ['What specific courses in the program?', 'How different from home country?', 'Faculty research interests?']
    },
    
    // Financial Questions
    {
      question: `Walk me through your ${data.sponsorType.toLowerCase()} funding - how will all expenses be covered without needing work?`,
      category: 'financial',
      riskLevel: financialRiskLevel,
      intent: 'Verify comprehensive financial planning',
      sampleAnswer: `My ${data.sponsorType.toLowerCase()} has allocated funds specifically for this education. We've accounted for tuition (${getTuitionEstimate(data.country)}), living costs, insurance, and emergencies with a ${getBufferPercentage()} buffer.`,
      officerIntent: 'Check if student has realistic financial planning vs vague assurances',
      commonMistakes: ['Unclear breakdown', 'Relying on future work', 'No emergency funds'],
      likelyFollowUps: ['Show me bank statements?', 'Sponsor occupation and income?', 'What if costs increase?']
    },
    
    // Return Intent Questions
    {
      question: `Describe exactly what position you'll seek in ${getHomeCountry()} after graduation and why they'll hire you over local graduates?`,
      category: 'return_intent',
      riskLevel: 'high',
      intent: 'Test concrete, realistic return plan',
      sampleAnswer: `I'll target ${getTargetRoles(data.course)} roles at companies like ${getTargetCompanies(data.course)} where my international perspective on ${getInternationalEdge(data.course)} combined with local market knowledge from my ${data.workExperience || ''} years experience creates unique value.`,
      officerIntent: 'Verify specific, plausible career path vs vague aspirations',
      commonMistakes: ['Vague "good job" statements', 'No specific companies', 'Underestimating competition'],
      likelyFollowUps: ['Starting salary expectations?', 'Contacts at these companies?', 'Why not work abroad first?']
    },
    
    // Background Questions - Dynamic based on profile
    {
      question: `How does your background in ${getBackgroundSummary(data)} prepare you for the challenges of ${data.degreeLevel.toLowerCase()} studies in ${data.country}?`,
      category: 'background',
      riskLevel: backgroundRiskLevel,
      intent: 'Assess self-awareness of academic transition',
      sampleAnswer: `My experience with ${getRelevantExperience(data)} has taught me ${getLearnedSkills(data)} which directly applies to ${getCourseApplication(data.course)}. I've specifically prepared by ${getPreparationSteps(data)}.`,
      officerIntent: 'Check if student understands academic demands and has prepared',
      commonMistakes: ['Overconfidence', 'No specific preparation', 'Underestimating cultural/academic differences'],
      likelyFollowUps: ['Biggest challenge you anticipate?', 'Academic support you\'ll use?', 'How handle language/cultural barriers?']
    },
    
    // Course-Specific Questions
    {
      question: `What specific problems in ${getIndustryField(data.course)} do you hope to solve with this ${data.course}, and why can't you learn this in your home country?`,
      category: 'study_intent',
      riskLevel: 'medium',
      intent: 'Test deep course motivation and local alternatives',
      sampleAnswer: `In ${getHomeCountry()}, we face challenges with ${getLocalProblems(data.course)}. ${data.country} leads in ${getCountryExpertise(data.country, data.course)} which ${data.universityType} specializes in through their ${getProgramFeatures(data.course)} approach not available locally.`,
      officerIntent: 'Verify genuine need for international education vs convenience',
      commonMistakes: ['Generic "better quality"', 'No specific local problems', 'Unaware of home country options'],
      likelyFollowUps: ['Specific courses addressing this?', 'Professors working on this?', 'How transfer knowledge home?']
    }
  ];
  
  return variants[index % variants.length];
};
  
  // Generate unique questions
  for (let i = 0; i < count && questions.length < count; i++) {
    const variant = generateVariant(i);
    
    // Personalize the template
    const personalizedQuestion = personalizeQuestion(variant, data, i);
    
    // Ensure uniqueness
    if (!usedQuestions.has(personalizedQuestion.question)) {
      usedQuestions.add(personalizedQuestion.question);
      questions.push(personalizedQuestion);
    }
  }
  
  // If we still need more questions, generate based on specific risk factors
  if (questions.length < count) {
    const riskBasedQuestions = generateRiskBasedQuestions(data, count - questions.length, usedQuestions);
    questions.push(...riskBasedQuestions);
  }
  
  return questions.slice(0, count);
}

// Helper to personalize questions
function personalizeQuestion(template: Question, data: InterviewRequest, index: number): Question {
  const personalized = { ...template };
  
  // Replace placeholders with actual data
  personalized.question = personalized.question
    .replace('${course}', data.course)
    .replace('${universityType}', data.universityType)
    .replace('${degreeLevel}', data.degreeLevel.toLowerCase())
    .replace('${sponsorType}', data.sponsorType.toLowerCase())
    .replace('${country}', data.country);
  
  // Personalize sample answer
  personalized.sampleAnswer = personalized.sampleAnswer
    .replace('${course}', data.course)
    .replace('${workExperience}', data.workExperience?.toString() || '')
    .replace('${age}', data.age?.toString() || '')
    .replace('${studyGap}', data.studyGap);
  
  // Add variation based on index
  if (index > 0) {
    // Add follow-up variations for subsequent questions
    const variations = [
      'Given your specific situation, ',
      'Considering your background, ',
      'In light of your chosen course, ',
      'Based on your profile, '
    ];
    
    if (!personalized.question.startsWith(variations[0])) {
      const variation = variations[index % variations.length];
      personalized.question = variation + personalized.question.toLowerCase();
    }
  }
  
  return personalized;
}

// Generate questions based on specific risk factors
function generateRiskBasedQuestions(data: InterviewRequest, count: number, usedQuestions: Set<string>): Question[] {
  const questions: Question[] = [];
  const riskFactors: Array<{type: string, generate: () => Question}> = [];
  
  // Identify risk factors and generate specific questions
  if (parseInt(data.studyGap) > 0) {
    riskFactors.push({
      type: 'studyGap',
      generate: () => ({
        question: `During your ${data.studyGap} gap, what specific industry trend in ${getIndustryField(data.course)} convinced you that formal education was necessary now?`,
        category: 'background' as const,
        riskLevel: parseInt(data.studyGap) > 2 ? 'high' : 'medium' as const,
        intent: 'Test industry awareness and timing justification',
        sampleAnswer: `The ${data.studyGap} gap revealed that ${getIndustryTrend(data.course)} requires formal training in ${getSpecificSkills(data.course)}. I witnessed ${getGapObservation(data)} which showed me the limitations of self-learning versus structured education.`,
        officerIntent: 'Verify productive gap and current industry knowledge',
        commonMistakes: ['No specific trends mentioned', 'Vague "needed update"', 'No evidence of staying current'],
        likelyFollowUps: ['Specific technologies emerged?', 'Industry reports you followed?', 'How did you research programs?']
      })
    });
  }
  
  if (data.sponsorType === 'Relative') {
    riskFactors.push({
      type: 'relativeSponsor',
      generate: () => ({
        question: `What makes your ${data.sponsorType.toLowerCase()} willing to invest such significant funds in your education versus their own children or closer relatives?`,
        category: 'financial' as const,
        riskLevel: 'high' as const,
        intent: 'Test authenticity of relative sponsorship relationship',
        sampleAnswer: `As my ${getRelativeRelation()}, they've seen my dedication to ${getPersonalAchievement()} and believe in my potential to ${getFamilyBenefit()}. This investment aligns with our family values of ${getFamilyValues()} and my commitment to ${getRepaymentCommitment()}.`,
        officerIntent: 'Verify genuine family relationship versus financial transaction',
        commonMistakes: ['Unclear relationship dynamics', 'Business-like arrangements', 'Unrealistic repayment promises'],
        likelyFollowUps: ['Exact family position?', 'Previous financial support?', 'Expectations after graduation?']
      })
    });
  }
  
  if (data.previousRefusals) {
    riskFactors.push({
      type: 'previousRefusal',
      generate: () => ({
        question: `What did you learn from your previous refusal that fundamentally changed how you approached this application?`,
        category: 'background' as const,
        riskLevel: 'high' as const,
        intent: 'Test growth and application improvement',
        sampleAnswer: `The refusal taught me the importance of ${getRefusalLesson()}. This time, I've ${getImprovementActions()} and can demonstrate ${getNewEvidence()} that directly addresses the previous concerns about ${getPreviousConcern()}.`,
        officerIntent: 'Verify substantial improvement vs cosmetic changes',
        commonMistakes: ['Blaming officer/system', 'No specific changes', 'Same application with minor tweaks'],
        likelyFollowUps: ['Exact refusal reason?', 'New documents?', 'Different university choice reason?']
      })
    });
  }
  
  if (data.ieltsScore && data.ieltsScore < 6.5) {
    riskFactors.push({
      type: 'languageScore',
      generate: () => ({
        question: `With an IELTS score of ${data.ieltsScore}, how will you handle complex academic discussions and rigorous coursework in English?`,
        category: 'background' as const,
        riskLevel: 'high' as const,
        intent: 'Test language preparedness and improvement plan',
        sampleAnswer: `I recognize my ${data.ieltsScore} score needs improvement. I've already ${getLanguagePreparation()} and will ${getUniversityLanguageSupport()}. My strength in ${getLanguageStrength()} helps with ${getAcademicCompensation()}.`,
        officerIntent: 'Verify realistic language plan versus wishful thinking',
        commonMistakes: ['Overconfidence', 'No specific improvement plan', 'Underestimating academic demands'],
        likelyFollowUps: ['English courses planned?', 'Academic support you\'ll use?', 'How handle group projects?']
      })
    });
  }
  
  // Generate questions from risk factors
  for (let i = 0; i < Math.min(count, riskFactors.length); i++) {
    const question = riskFactors[i].generate();
    if (!usedQuestions.has(question.question)) {
      usedQuestions.add(question.question);
      questions.push(question);
    }
  }
  
  return questions;
}

// Country insights with detailed psychology
const COUNTRY_TEMPLATES: Record<string, any> = {
  'UK': {
    focus: ['Academic progression logic', 'Course relevance to background', 'Career plans in home country', 'Financial sustainability without work'],
    officerMindset: ['Hates vague answers about "better education"', 'Values specific university research evidence over rankings', 'Suspicious of field changes without justification', 'Verifies funds can cover entire stay'],
    avoid: ['Settlement intentions or PR plans', 'Generic statements', 'Unclear career progression', 'Mentioning family in UK', 'Wanting to work during studies']
  },
  'Canada': {
    focus: ['Genuine Student Intent (GSI) proof', 'Financial capacity with source verification', 'Strong return intent with concrete plans', 'Academic capability for program'],
    officerMindset: ['Very strict on post-study return evidence', 'Deeply verifies sponsor credibility and source', 'Suspicious of any PR or settlement discussions', 'Wants concrete home country ties (property, family, job prospects)'],
    avoid: ['Permanent residency plans', 'Family migration intentions', 'Weak home country connections', 'Unclear sponsor relationships', 'Career plans in Canada']
  },
  'USA': {
    focus: ['Non-immigrant intent proof', 'Strong family/business/property ties to home country', 'Academic excellence and capability', 'Financial stability without US work'],
    officerMindset: ['Focuses intensely on proving no immigration intent', 'Values strong ties that guarantee return', 'Suspicious of students with family in USA', 'Checks for previous visa denials or violations'],
    avoid: ['Any immigration intent discussions', 'Family members living in USA', 'Long-term stay plans', 'Career opportunities in USA', 'Weak home country connections']
  },
  'Australia': {
    focus: ['Genuine Temporary Entrant (GTE) assessment', 'Course value for home country development', 'Financial capacity for entire stay', 'English proficiency for academic success'],
    officerMindset: ['Assesses genuine temporary stay intention', 'Looks for course relevance to home country needs', 'Verifies sustainable funds without work dependence', 'Wants clear post-study departure evidence'],
    avoid: ['Permanent migration discussions', 'Overstaying history or intent', 'Weak home ties', 'Unclear study motivations', 'Financial dependence on Australian work']
  },
  'default': {
    focus: ['Study intent verification', 'Financial capacity proof', 'Return plan clarity', 'Academic capability'],
    officerMindset: ['Wants genuine student intent over immigration', 'Verifies financial sustainability', 'Checks strong home country ties', 'Looks for specific details not vague answers'],
    avoid: ['Settlement or immigration intentions', 'Vague career plans', 'Financial dependence on work', 'Weak home connections', 'Contradictory statements']
  }
};

export async function POST(request: NextRequest) {


  // Authorization check - ADD THIS
const comingHeaders = request.headers.get("authorization");

if(comingHeaders !== process.env.APP_API_KEY) {
  return NextResponse.json(
    { success: false, message: 'Unauthorized Access' },
    { status: 401 }
  );
}
  
  const startTime = Date.now();
  
  try {
    // Check authentication
    const auth = await checkAuth(request);
    const questionCount = auth.isFullUser ? 15 : 5;
    
    // Parse request body
    const body: InterviewRequest = await request.json();
    
    // Validate required fields
    if (!body.country || !body.course || !body.degreeLevel) {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Country, Course, and Degree Level are required fields' 
        },
        { status: 400 }
      );
    }

    // Calculate detailed risk profile
    const riskProfile = calculateRiskProfile(body);
    
    let questions: Question[] = [];
    let aiGenerated = true;
    let errorMessage = '';

    try {
      // Generate TRULY personalized questions
      questions = await generatePersonalizedQuestionsWithDeepSeek(body, riskProfile, questionCount);
      console.log(`Generated ${questions.length} PERSONALIZED questions for ${body.country} - ${body.course}`);
    } catch (apiError) {
      console.warn('DeepSeek personalized generation failed:', apiError);
      aiGenerated = false;
      errorMessage = apiError instanceof Error ? apiError.message : 'API call failed';
      
      // Use advanced fallback with some personalization
      questions = generateAdditionalPersonalizedQuestions(body, questionCount);
    }

    // Get country insights
    const countryInsights = COUNTRY_TEMPLATES[body.country] || COUNTRY_TEMPLATES.default;

    const response: PredictionResponse = {
      interviewReadinessScore: riskProfile.score,
      confidence: aiGenerated ? 0.92 : 0.7, // Higher confidence for personalized AI
      riskLevel: riskProfile.risk,
      topQuestions: questions,
      weakAreas: riskProfile.weakAreas,
      countryInsights,
      generatedAt: new Date().toISOString(),
      disclaimer: 'AI-generated personalized embassy interview prediction based on YOUR specific profile. Questions are tailored to your unique risk factors. Actual interview may vary.'
    };

    // Set limited access for non-full users
    if (!auth.isFullUser) {
      response.limited = true;
      response.totalQuestions = 15;
      response.unlockMessage = 'Sign up to unlock all 15 personalized questions with detailed analysis';
    }

    const processingTime = Date.now() - startTime;

    return NextResponse.json({
      success: true,
      data: response,
      meta: {
        processingTime: `${processingTime}ms`,
        aiGenerated,
        personalized: true,
        questionCount: questions.length,
        authenticated: auth.isValid,
        userType: auth.isFullUser ? 'full' : (auth.isValid ? 'limited' : 'guest'),
        profileAnalyzed: {
          country: body.country,
          course: body.course,
          degreeLevel: body.degreeLevel,
          riskFactors: riskProfile.personalizedRiskFactors.length,
          uniqueQuestions: questions.filter((q, i, arr) => 
            arr.findIndex(q2 => q2.question === q.question) === i
          ).length
        }
      }
    });

  } catch (error: any) {
    console.error('Server error:', error);
    
    try {
      const body: InterviewRequest = await request.json();
      const auth = await checkAuth(request);
      const questionCount = auth.isFullUser ? 15 : 5;
      
      const riskProfile = calculateRiskProfile(body);
      const questions = generateAdditionalPersonalizedQuestions(body, questionCount);
      const countryInsights = COUNTRY_TEMPLATES[body.country] || COUNTRY_TEMPLATES.default;
      
      const fallbackResponse: PredictionResponse = {
        interviewReadinessScore: riskProfile.score,
        confidence: 0.65,
        riskLevel: riskProfile.risk,
        topQuestions: questions,
        weakAreas: riskProfile.weakAreas,
        countryInsights,
        generatedAt: new Date().toISOString(),
        disclaimer: 'Local personalized prediction. AI service temporarily unavailable. Questions tailored to your specific profile factors.'
      };
      
      if (!auth.isFullUser) {
        fallbackResponse.limited = true;
        fallbackResponse.totalQuestions = 15;
      }
      
      return NextResponse.json({
        success: true,
        data: fallbackResponse,
        meta: {
          fallback: true,
          personalized: true,
          message: 'Using personalized local generation',
          profileFactors: riskProfile.personalizedRiskFactors.length
        }
      });
    } catch {
      return NextResponse.json(
        { 
          success: false, 
          error: 'Personalized prediction service unavailable. Please try again later.'
        },
        { status: 500 }
      );
    }
  }
}

export async function GET() {
  return NextResponse.json({
    status: 'active',
    version: '6.0',
    features: [
      'Deeply personalized AI-generated questions',
      'Profile-specific risk factor analysis',
      'Dynamic question generation based on ALL input data',
      'Country-specific officer psychology insights',
      'No template questions - every question is unique to the profile'
    ],
    note: 'This API generates UNIQUE questions for EACH profile, not template-based questions'
  });
}