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

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

interface VisaPredictionRequest {
  destinationCountry: string;
  visaType: string;
  age: number;
  educationLevel: string;
  educationGapYears: number;
  employmentStatus: string;
  jobExperienceYears: number;
  previousRefusals: number;
  financialSource: string;
  financialProofAmount: number;
  languageTest: string;
  languageScore: number | null;
  mediumOfInstruction: string;
  purposeOfTravel: string;
  familyTiesInHomeCountry: string;
  travelHistory: string[];
  residenceCountry: string;
  residenceCity: string;
  // For backwards compatibility
  country: string;
  ieltsScore: number | null;
}

interface RiskFactor {
  factor: string;
  severity: 'low' | 'medium' | 'high';
  description: string;
  impact: number;
}

interface ImprovementSuggestion {
  suggestion: string;
  priority: 'high' | 'medium' | 'low';
  action: string;
  timeline: string;
}

interface VisaPredictionResponse {
  successProbability: number;
  confidence: number;
  riskLevel: 'low' | 'medium' | 'high';
  predictedOutcome: 'recommended_for_approval' | 'recommended_for_refusal' | 'borderline';
  keyStrengths: string[];
  riskFactors: RiskFactor[];
  improvementSuggestions: ImprovementSuggestion[];
  countrySpecificAdvice: string[];
  processingTimeEstimate: string;
  documentChecklist: string[];
  estimatedVisaFee: number;
  nextSteps: string[];
  disclaimer: string;
  generatedAt: string;
  aiModelUsed: string;
  tokenUsage?: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

// Country-specific visa statistics and requirements
const COUNTRY_VISA_DATA = {
  'Canada': {
    baseSuccessRate: 0.65,
    riskFactors: [
      'Financial insufficiency',
      'Lack of ties to home country',
      'Education mismatch',
      'Travel history'
    ],
    averageProcessingTime: '8-12 weeks',
    visaFee: 185
  },
  'USA': {
    baseSuccessRate: 0.60,
    riskFactors: [
      '214(b) - Immigrant intent',
      'Financial constraints',
      'Inconsistent documentation',
      'Employment history'
    ],
    averageProcessingTime: '3-8 weeks',
    visaFee: 185
  },
  'UK': {
    baseSuccessRate: 0.70,
    riskFactors: [
      'Genuineness of study',
      'Financial maintenance',
      'Previous refusals',
      'Credibility'
    ],
    averageProcessingTime: '3 weeks',
    visaFee: 490
  },
  'Australia': {
    baseSuccessRate: 0.75,
    riskFactors: [
      'GTE (Genuine Temporary Entrant)',
      'Financial capacity',
      'English proficiency',
      'Health requirements'
    ],
    averageProcessingTime: '1-4 months',
    visaFee: 710
  },
  'Germany': {
    baseSuccessRate: 0.80,
    riskFactors: [
      'Financial proof',
      'University admission',
      'German language (if applicable)',
      'Previous refusals'
    ],
    averageProcessingTime: '4-12 weeks',
    visaFee: 75
  },
  'New Zealand': {
    baseSuccessRate: 0.78,
    riskFactors: [
      'Genuine intentions',
      'Financial support',
      'Return ticket',
      'Accommodation proof'
    ],
    averageProcessingTime: '20-25 days',
    visaFee: 375
  },
  'UAE': {
    baseSuccessRate: 0.85,
    riskFactors: [
      'Employment offer',
      'Salary requirements',
      'Medical fitness',
      'Security clearance'
    ],
    averageProcessingTime: '2-3 weeks',
    visaFee: 300
  },
  'Singapore': {
    baseSuccessRate: 0.72,
    riskFactors: [
      'Employment pass eligibility',
      'Salary requirements',
      'Qualifications recognition',
      'Quota availability'
    ],
    averageProcessingTime: '1-8 weeks',
    visaFee: 90
  }
};

// Language test score validation
const LANGUAGE_TEST_REQUIREMENTS = {
  ielts: { min: 0, max: 9, description: 'IELTS score (0-9)' },
  toefl: { min: 0, max: 120, description: 'TOEFL score (0-120)' },
  pte: { min: 0, max: 90, description: 'PTE Academic score (0-90)' },
  celpip: { min: 0, max: 12, description: 'CELPIP score (0-12)' },
  duolingo: { min: 10, max: 160, description: 'Duolingo English Test score (10-160)' },
  cael: { min: 0, max: 90, description: 'CAEL score (0-90)' }
};

async function getAIPrediction(data: VisaPredictionRequest): Promise<VisaPredictionResponse> {
  const startTime = Date.now();
  
  if (!DEEPSEEK_API_KEY) {
    return generateFallbackPrediction(data);
  }

  try {
    const countryData = COUNTRY_VISA_DATA[data.destinationCountry as keyof typeof COUNTRY_VISA_DATA];
    
    const systemPrompt = `You are an expert visa assessment AI with access to global visa statistics and patterns. 
Analyze the applicant's profile and provide a detailed visa chance prediction.

APPLICANT INFORMATION:
- From: ${data.residenceCity ? `${data.residenceCity}, ` : ''}${data.residenceCountry}
- Destination: ${data.destinationCountry}
- Visa Type: ${data.visaType}

COUNTRY-SPECIFIC CONSIDERATIONS for ${data.destinationCountry}:
${countryData ? 
  `Base Success Rate: ${countryData.baseSuccessRate * 100}%
Common Risk Factors: ${countryData.riskFactors.join(', ')}
Average Processing Time: ${countryData.averageProcessingTime}
Visa Fee: $${countryData.visaFee}` : 
  'Use general international standards'}

LANGUAGE PROFICIENCY:
${data.languageTest && data.languageTest !== 'not_applicable' ? 
  `Test: ${data.languageTest.toUpperCase()}
Score: ${data.languageScore || 'Not provided'}` : 
  'No language test provided'}

ANALYSIS GUIDELINES:
1. Previous refusals significantly impact chances (each refusal reduces probability by 15-25%)
2. Education gaps > 2 years require strong justification
3. Financial proof must cover 1.5x estimated expenses
4. Strong home country ties improve chances by 20-30%
5. Travel history to visa-compliant countries improves credibility
6. Consider applicant's country of residence and specific circumstances

RESPONSE FORMAT (must be valid JSON):
{
  "successProbability": number (0-100),
  "confidence": number (0-1),
  "riskLevel": "low" | "medium" | "high",
  "predictedOutcome": "recommended_for_approval" | "recommended_for_refusal" | "borderline",
  "keyStrengths": string[],
  "riskFactors": [{"factor": string, "severity": "low" | "medium" | "high", "description": string, "impact": number}],
  "improvementSuggestions": [{"suggestion": string, "priority": "high" | "medium" | "low", "action": string, "timeline": string}],
  "countrySpecificAdvice": string[],
  "processingTimeEstimate": string,
  "documentChecklist": string[],
  "estimatedVisaFee": number,
  "nextSteps": string[],
  "disclaimer": string
}`;

    const userPrompt = `Visa Prediction Request:

DESTINATION: ${data.destinationCountry} (${data.visaType})
APPLICANT FROM: ${data.residenceCity ? `${data.residenceCity}, ` : ''}${data.residenceCountry}

APPLICANT PROFILE:
- Age: ${data.age} years
- Education: ${data.educationLevel} (Gap: ${data.educationGapYears} years)
- Employment: ${data.employmentStatus} (${data.jobExperienceYears} years experience)
- Financial: ${data.financialSource} ($${data.financialProofAmount})
- Language: ${data.languageTest ? `${data.languageTest.toUpperCase()} ${data.languageScore || 'No score'}` : 'Not provided'}

TRAVEL HISTORY:
- Previous Refusals: ${data.previousRefusals}
- Countries Visited: ${data.travelHistory.join(', ') || 'None'}

PERSONAL CIRCUMSTANCES:
- Purpose: ${data.purposeOfTravel}
- Family Ties: ${data.familyTiesInHomeCountry}
- Medium of Instruction: ${data.mediumOfInstruction}

Based on ${data.destinationCountry}'s requirements and global patterns, provide assessment.`;

    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: systemPrompt },
          { role: 'user', content: userPrompt }
        ],
        temperature: 0.1,
        max_tokens: 2000
      })
    });

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

    const result = await response.json();
    const aiResponse = result.choices[0]?.message?.content;
    const tokenUsage = result.usage;

    // Parse JSON from AI response
    const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      throw new Error('Invalid AI response format');
    }

    const prediction: VisaPredictionResponse = JSON.parse(jsonMatch[0]);
    
    // Enhance with additional data
    if (countryData) {
      prediction.estimatedVisaFee = countryData.visaFee;
      prediction.processingTimeEstimate = countryData.averageProcessingTime;
    }

    // Add metadata
    prediction.generatedAt = new Date().toISOString();
    prediction.aiModelUsed = 'deepseek-chat';
    prediction.tokenUsage = tokenUsage;
    prediction.disclaimer = 'This prediction is based on AI analysis of provided information and historical visa patterns. It is not a guarantee of visa approval. Consult with a licensed immigration consultant for personalized advice.';

    return prediction;

  } catch (error) {
    console.error('AI Prediction error:', error);
    return generateFallbackPrediction(data);
  }
}

function generateFallbackPrediction(data: VisaPredictionRequest): VisaPredictionResponse {
  const baseScore = 70;
  let score = baseScore;
  const riskFactors: RiskFactor[] = [];
  const strengths: string[] = [];

  // Calculate score adjustments
  if (data.previousRefusals > 0) {
    score -= data.previousRefusals * 15;
    riskFactors.push({
      factor: 'Previous visa refusals',
      severity: 'high',
      description: `${data.previousRefusals} previous refusal(s) significantly impact credibility`,
      impact: -20
    });
  }

  if (data.educationGapYears > 2) {
    score -= 10;
    riskFactors.push({
      factor: 'Education gap',
      severity: data.educationGapYears > 5 ? 'high' : 'medium',
      description: `Education gap of ${data.educationGapYears} years requires strong justification`,
      impact: -15
    });
  }

  // Language test validation
  if (data.languageTest && data.languageTest !== 'not_applicable' && data.languageScore) {
    const requirements = LANGUAGE_TEST_REQUIREMENTS[data.languageTest as keyof typeof LANGUAGE_TEST_REQUIREMENTS];
    if (requirements) {
      const normalizedScore = (data.languageScore - requirements.min) / (requirements.max - requirements.min) * 100;
      if (normalizedScore < 60) {
        score -= 15;
        riskFactors.push({
          factor: 'Language proficiency',
          severity: 'high',
          description: `${data.languageTest.toUpperCase()} score of ${data.languageScore} may not meet minimum requirements`,
          impact: -20
        });
      } else if (normalizedScore >= 80) {
        score += 10;
        strengths.push('Strong language proficiency');
      }
    }
  }

  if (data.financialSource === 'Personal savings') {
    score += 10;
    strengths.push('Strong financial independence');
  }

  if (data.travelHistory.length > 0) {
    score += 10;
    strengths.push('Positive travel history to compliant countries');
  }

  if (data.familyTiesInHomeCountry === 'Strong (own property, immediate family)') {
    score += 15;
    strengths.push('Strong ties to home country');
  }

  // Adjust based on residence country
  if (data.residenceCountry) {
    // Countries with traditionally higher visa approval rates
    const favorableCountries = ['USA', 'UK', 'Canada', 'Australia', 'Germany', 'France', 'Japan', 'Singapore'];
    if (favorableCountries.includes(data.residenceCountry)) {
      score += 5;
      strengths.push(`Favorable residence country (${data.residenceCountry})`);
    }
  }

  // Clamp score
  score = Math.max(20, Math.min(95, score));

  // Determine risk level
  let riskLevel: 'low' | 'medium' | 'high' = 'medium';
  if (score >= 75) riskLevel = 'low';
  if (score <= 40) riskLevel = 'high';

  // Determine outcome
  let predictedOutcome: 'recommended_for_approval' | 'recommended_for_refusal' | 'borderline' = 'borderline';
  if (score >= 70) predictedOutcome = 'recommended_for_approval';
  if (score <= 45) predictedOutcome = 'recommended_for_refusal';

  const countryData = COUNTRY_VISA_DATA[data.destinationCountry as keyof typeof COUNTRY_VISA_DATA];

  return {
    successProbability: score,
    confidence: 0.85,
    riskLevel,
    predictedOutcome,
    keyStrengths: strengths,
    riskFactors,
    improvementSuggestions: [
      {
        suggestion: 'Strengthen financial documentation',
        priority: 'high',
        action: 'Provide bank statements for last 6 months with consistent balance',
        timeline: 'Immediate'
      },
      {
        suggestion: 'Prepare strong Statement of Purpose',
        priority: 'medium',
        action: 'Clearly articulate purpose of travel and return plans',
        timeline: 'Before application'
      },
      {
        suggestion: 'Improve language proficiency if needed',
        priority: data.languageScore && data.languageScore < 6 ? 'high' : 'low',
        action: 'Take language preparation course if score is low',
        timeline: '1-2 months'
      }
    ],
    countrySpecificAdvice: [
      `Check ${data.destinationCountry} embassy website for latest requirements`,
      'All documents must be translated and attested if required',
      'Schedule appointment well in advance'
    ],
    processingTimeEstimate: countryData?.averageProcessingTime || '4-8 weeks',
    documentChecklist: [
      'Valid passport',
      'Completed visa application form',
      'Passport-sized photographs',
      'Proof of financial means',
      'Travel itinerary',
      'Accommodation details',
      'Travel insurance',
      'Language test results (if applicable)',
      'Educational certificates',
      'Employment verification'
    ],
    estimatedVisaFee: countryData?.visaFee || 185,
    nextSteps: [
      'Gather all required documents',
      'Book visa appointment',
      'Prepare for visa interview',
      'Consider professional consultation'
    ],
    disclaimer: 'This is an automated assessment based on general patterns. Actual visa decision depends on consular officer assessment.',
    generatedAt: new Date().toISOString(),
    aiModelUsed: 'fallback-algorithm'
  };
}

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 }
  );
}
  
  try {
    const body = await request.json();
    
    // Validate required fields
    if (!body.destinationCountry || !body.visaType || !body.residenceCountry) {
      return NextResponse.json(
        { error: 'Destination country, visa type, and country of residence are required' },
        { status: 400 }
      );
    }

    // For backwards compatibility
    if (!body.country) {
      body.country = body.destinationCountry;
    }
    if (!body.ieltsScore && body.languageTest === 'ielts') {
      body.ieltsScore = body.languageScore;
    }

    const prediction = await getAIPrediction(body);

    return NextResponse.json({
      success: true,
      data: prediction,
      timestamp: new Date().toISOString()
    });

  } catch (error: any) {
    console.error('Prediction API error:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error.message || 'Prediction failed',
        data: null 
      },
      { status: 500 }
    );
  }
}

// Also support GET for testing
export async function GET(request: NextRequest) {
  return NextResponse.json({
    success: true,
    message: 'Visa prediction API is running',
    endpoints: ['POST /api/frontend/ai-visa-predictor']
  });
}


