import { NextRequest, NextResponse } from "next/server";
import OpenAI from 'openai';
import pool from '../../../../lib/db/db';

const deepseek = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY || '',
  baseURL: 'https://api.deepseek.com',
});

export async function POST(request: NextRequest) {

        const commingHeaders = request.headers.get("authorization");

    if(commingHeaders !== process.env.APP_API_KEY)
    {
        return NextResponse.json(
            { success: false, message: 'Unauthorized Access' },
            { status: 401 }
        );
    }
  
  let connection;
  let planId: number | null = null;
  
  try {
    const body = await request.json();
    
    const {
      fullName,
      email,
      phone,
      nationality,
      lastEducation,
      educationLevel,
      cgpa,
      studyGap,
      gapJustification,
      country,
      university,
      course,
      wordCount = '500-600',
      responseStyle = 'professional',
      englishTest,
      englishScore
    } = body;

    if (!fullName || !email || !lastEducation || !country || !university || !course) {
      return new Response(
        JSON.stringify({ 
          error: 'Missing required fields. Please fill in all required information.' 
        }),
        { 
          status: 400, 
          headers: { 'Content-Type': 'application/json' }
        }
      );
    }

    if (!process.env.DEEPSEEK_API_KEY) {
      console.error('DEEPSEEK_API_KEY is not configured');
      return new Response(
        JSON.stringify({ error: 'AI service is currently unavailable. Please try again later.' }),
        { 
          status: 500, 
          headers: { 'Content-Type': 'application/json' }
        }
      );
    }

    connection = await pool.getConnection();

    // Insert into database and get the planId
    const [result] = await connection.execute(
      `INSERT INTO study_plans (
        full_name, email, phone, nationality, last_education, education_level, 
        cgpa, study_gap, gap_justification, target_country, target_university, 
        target_course, word_count, response_style, english_test, english_score, study_plan
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        fullName.trim(),
        email.trim().toLowerCase(),
        phone ? phone.trim() : null,
        nationality ? nationality.trim() : null,
        lastEducation.trim(),
        educationLevel || null,
        cgpa || null,
        studyGap || null,
        gapJustification || null,
        country.trim(),
        university.trim(),
        course.trim(),
        wordCount,
        responseStyle,
        englishTest || null,
        englishScore || null,
        'Generating...',
      ]
    );

    planId = (result as any).insertId;
    
    if (!planId) {
      throw new Error('Failed to save study plan record');
    }

    // Format English test information
    const englishTestInfo = englishTest === 'none' 
      ? 'No English proficiency test taken'
      : `${englishTest.toUpperCase()}${englishScore ? `: ${englishScore}` : ' (score not provided)'}`;

    const prompt = `Generate a Motivational Letter in CLEAN, SIMPLE HTML without ANY CSS, styles, or formatting.

STUDENT PROFILE:
Full Name: ${fullName}
Nationality: ${nationality || 'Not specified'}
Academic Background: ${lastEducation} ${educationLevel ? `(${educationLevel})` : ''}
Academic Performance: ${cgpa || 'Not specified'}
Study Gap: ${studyGap || 'None'}
Gap Justification/Experience: ${gapJustification || 'Not specified'}
English Proficiency: ${englishTestInfo}

TARGET ACADEMIC GOALS:
Destination Country: ${country}
Target University: ${university}
Desired Program: ${course}

RESPONSE REQUIREMENTS:
- Generate ONLY semantic HTML tags
- NO CSS styles, NO style attributes, NO classes
- NO <style> tags, NO <div> tags
- Use only: <h1>, <h2>, <h3>, <p>, <ul>, <ol>, <li>, <strong>, <em>
- NO markdown symbols (**, *, #, etc.)
- NO width, height, margin, padding, or positioning
- Just clean semantic HTML

FORMAT:
<h1>Main Title</h1>
<h2>Section Title</h2>
<p>Paragraph text</p>
<ul>
<li>Bullet point 1</li>
<li>Bullet point 2</li>
</ul>
<ol>
<li>Step 1</li>
<li>Step 2</li>
</ol>

OBJECTIVE:
Write a high-impact, visa-approved Study Plan / Statement of Purpose that:
	•	Clearly justifies WHY this country
	•	Clearly explains WHY this university
	•	Strongly proves WHY this course
	•	Shows logical academic & career progression
	•	Demonstrates strong home-country ties & return intent
	•	Aligns with visa officer psychology

WRITING STYLE & RULES:
	•	Tone: Professional, confident, genuine, visa-friendly
	•	Language: Clear, formal, non-memorized, human-like
	•	Avoid over-dramatic language or emotional stories
	•	Avoid plagiarism or generic phrases
	•	Avoid mentioning immigration or PR intentions
	•	Focus on education-driven motivation

MANDATORY STRUCTURE (DO NOT CHANGE ORDER):
	1.	Introduction & Academic Background
	2.	Motivation for the Chosen Field of Study
	3.	Why This Country (Education System + Industry Relevance)
	4.	Why This University (Facilities, Curriculum, Ranking, Practical Exposure)
	5.	Course Relevance to Previous Studies & Career
	6.	Career Plan After Graduation (Return to Home Country)
	7.	Financial Capability & Sponsorship
	8.	Conclusion (Strong, Positive, Forward-Looking)

LWNGTH REQUIREMENT:
	•	${wordCount} words
	•	Clear paragraphs with strong logical flow

IMPORTANT NOTES:
- Keep the tone natural and convincing within the given word limit
- Bold important academic achievements and qualifications using <strong> tags
- Mention specific course modules or research areas that interest you
- Explain cultural adaptability if changing countries
- For Pakistani students, mention the educational context and aspirations
- If English test score is provided, highlight it appropriately`;

    const encoder = new TextEncoder();
    let accumulatedResponse = '';

    const stream = new ReadableStream({
      async start(controller) {
        try {
          // Send the planId as the first chunk
          controller.enqueue(encoder.encode(`<plan-id data-id="${planId}"></plan-id>`));
          
          const aiStream = await deepseek.chat.completions.create({
            model: 'deepseek-chat',
            messages: [
              {
                role: 'system',
                content: `You are a senior Study Plan & SOP writer with 15+ years of experience working with embassies, visa officers, and top international universities (Italy, France, Germany, UK, Canada, Australia, Romania, Cyprus, etc.). You fully understand visa refusal reasons, GTE / GS / Genuine Student rules, and how officers assess intent, financial credibility, academic progression, and home-country ties. Generate ONLY clean semantic HTML without any CSS, styles, or formatting. Use only: <h1>, <h2>, <h3>, <p>, <ul>, <ol>, <li>, <strong>, <em>. NO <div>, NO <style>, NO CSS, NO classes, NO style attributes. Just plain semantic HTML.`
              },
              {
                role: 'user',
                content: prompt
              }
            ],
            stream: true,
            max_tokens: 4000,
            temperature: 0.7,
          });

          for await (const chunk of aiStream) {
            const content = chunk.choices[0]?.delta?.content || '';
            if (content) {
              controller.enqueue(encoder.encode(content));
              accumulatedResponse += content;
            }
          }

          // Clean the response aggressively
          let cleanedResponse = accumulatedResponse
            // Remove any style tags
            .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
            // Remove any script tags
            .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
            // Remove all style attributes
            .replace(/ style="[^"]*"/g, '')
            // Remove all class attributes
            .replace(/ class="[^"]*"/g, '')
            // Remove all id attributes
            .replace(/ id="[^"]*"/g, '')
            // Remove div tags (opening and closing)
            .replace(/<div[^>]*>/gi, '')
            .replace(/<\/div>/gi, '')
            // Remove span tags
            .replace(/<span[^>]*>/gi, '')
            .replace(/<\/span>/gi, '')
            // Remove any inline CSS
            .replace(/width:\s*[^;]+;?/g, '')
            .replace(/height:\s*[^;]+;?/g, '')
            .replace(/margin:\s*[^;]+;?/g, '')
            .replace(/padding:\s*[^;]+;?/g, '')
            .replace(/position:\s*[^;]+;?/g, '')
            .replace(/display:\s*[^;]+;?/g, '')
            .replace(/float:\s*[^;]+;?/g, '')
            // Remove markdown
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            // Ensure proper HTML structure
            .trim();

          // If no h1, add one
          if (!cleanedResponse.includes('<h1>')) {
            cleanedResponse = `<h1>Study Plan for ${fullName}</h1>\n${cleanedResponse}`;
          }

          // Update database with final study plan
          await connection.execute(
            'UPDATE study_plans SET study_plan = ? WHERE id = ?',
            [cleanedResponse, planId]
          );

          controller.close();
          
        } catch (error) {
          console.error('Stream generation error:', error);
          
          if (connection && planId) {
            await connection.execute(
              'UPDATE study_plans SET study_plan = ? WHERE id = ?',
              ['<p>Error generating study plan. Please try again.</p>', planId]
            );
          }
          
          controller.enqueue(encoder.encode('<p>Error generating study plan. Please try again.</p>'));
          controller.close();
        } finally {
          if (connection) {
            connection.release();
          }
        }
      },
      
      cancel() {
        if (connection) {
          connection.release();
        }
      }
    });

    return new Response(stream, {
      headers: {
        'Content-Type': 'text/html; charset=utf-8',
        'Cache-Control': 'no-cache',
      },
    });

  } catch (error) {
    console.error('API endpoint error:', error);
    if (connection) connection.release();
    
    return new Response(
      JSON.stringify({ 
        error: 'Failed to generate study plan',
        details: process.env.NODE_ENV === 'development' ? (error as Error).message : undefined
      }),
      { 
        status: 500, 
        headers: { 'Content-Type': 'application/json' }
      }
    );
  }
}