import { NextResponse } from 'next/server';

export async function POST(request) {
  try {
    const body = await request.json();
    const { universityName, universityType, country, city, keywords = [] } = body;

    if (!universityName) {
      return NextResponse.json(
        { error: 'University name is required' },
        { status: 400 }
      );
    }

    // Check if DEEPSEEK_API_KEY is configured
    if (!process.env.DEEPSEEK_API_KEY) {
      return NextResponse.json(
        { error: 'DeepSeek API key is not configured' },
        { status: 500 }
      );
    }

    // Format keywords for the prompt - ENFORCE keyword usage
    const keywordsString = Array.isArray(keywords) && keywords.length > 0 
      ? `MANDATORY KEYWORDS TO INCLUDE NATURALLY: ${keywords.join(', ')}. You MUST incorporate ALL of these keywords organically throughout the article in relevant contexts.`
      : '';

    // Enhanced prompt with custom classes and refined requirements
    const systemPrompt = `You are a senior education content writer and SEO specialist with 20+ years of experience, specializing in international universities and study-abroad content. You write in clear, simple, human-like English, easy for students and parents to understand. Your writing must sound natural, informative, and trustworthy, not robotic or AI-generated.

IMPORTANT FORMATTING REQUIREMENTS:
1. Output ONLY the content inside <article> tags - NO <!DOCTYPE>, <html>, <head>, <title>, or <body> tags
2. Apply these EXACT CSS classes to elements:
   - For h1: class="sn-heading sn-heading-1"
   - For h2: class="sn-heading sn-heading-2"
   - For h3: class="sn-heading sn-heading-3"
   - For h4: class="sn-heading sn-heading-4"
   - For paragraphs: class="sn-paragraph"
   - For blockquotes: class="sn-blockquote"
   - For unordered lists: class="sn-list sn-ul"
   - For ordered lists: class="sn-list sn-ol"
   - For list items: class="sn-list-item"
   - For regular links (NOT custom buttons): class="sn-link"
   - For tables: class="sn-table sn-table-modern" (use as default)
3. Structure content with proper HTML tags only
4. DO NOT include any styling attributes (style="...") or inline CSS
5. Use semantic HTML with class attributes as specified above`;

    const userPrompt = `Write a 1000-word, 100% original, SEO-optimized article about the university:

University Name: ${universityName}
University Type: ${universityType || 'University'}
Country: ${country || 'the country'}
City: ${city || 'the city'}

${keywordsString}

⸻

✍️ CONTENT TASK

Write a 1000-word, 100% original, SEO-optimized article on the university.

The article must be well-structured, student-focused, and written in a conversational yet professional tone. Also please write FAQs in the Why choose us Section regarding the university. And also please add bullets point where possible. 

⸻

📚 CONTENT STRUCTURE (MANDATORY)

1️⃣ University Overview (200–250 words)
• Brief history and background
• Public or private status
• Global reputation and rankings (general, not exaggerated)
• Why international students choose this university
• Teaching style and academic strengths

⸻

2️⃣ Academic Programs & Major Courses (300–350 words)
• Overview of faculties and departments
• Popular Bachelor's, Master's, and PhD programs
• High-demand majors (Business, Engineering, IT, Health, Arts, etc.)
• Language of instruction (English / local language / bilingual)
• Industry relevance and career outcomes

⸻

3️⃣ Scholarships & Financial Support (250–300 words)
• Available scholarships for international students
• Government-funded vs university-funded scholarships
• Merit-based and need-based options
• Tuition fee waivers, grants, and discounts
• Simple explanation of eligibility (avoid complex legal terms)

⸻

5️⃣ Campus Life & Student Experience (250–300 words)
• Campus facilities (libraries, labs, sports, housing)
• Student clubs, societies, and cultural life
• Support services for international students
• Accommodation options (on-campus / off-campus)
• Safety, diversity, and inclusivity

⸻

6️⃣ Why Choose This University? (150–200 words)
• Key advantages over other universities
• Ideal student profile
• Career prospects after graduation
• Location benefits (city, lifestyle, cost of living)
• Also write 4-5 Minimum FAQ Regarding the University ${universityName}

⸻

🔍 SEO REQUIREMENTS (STRICT)
• Use natural keyword placement (no keyword stuffing)
• Include university name in headings and body
• Include country + "study in" phrases naturally
• Include "scholarships for international students" where relevant
• Include "programs", "courses", "tuition fees" organically
• Use short paragraphs (max 4-5 sentences each)
• Write plagiarism-free, original content
• Avoid copying statistics unless clearly paraphrased

⸻

🧠 WRITING STYLE GUIDELINES
• Human-like, not AI-sounding
• Simple language (Grade 8–10 readability)
• Student-friendly explanations
• No emojis
• No exaggerated marketing claims
• Avoid exact numbers unless widely known
• Neutral, informative, trustworthy tone

⸻

🚫 DO NOT
• Do not copy from official university websites
• Do not mention AI, ChatGPT, or prompts
• Do not include fake rankings or false claims
• Do not over-promise scholarships
• Do not use <!DOCTYPE>, <html>, <head>, <body>, or <title> tags
• Do not include inline CSS (style="...")
• Do not create tables unless absolutely necessary (avoid if possible)

⸻

✅ FINAL OUTPUT FORMAT (STRICT)
• Start with: <article>
• End with: </article>
• Inside article tags: Content ONLY with specified HTML structure
• Apply EXACT CSS classes as specified in system prompt
• Use proper heading hierarchy (h1, h2, h3, h4)
• Total length: Approx. 1500 words
• Must incorporate ALL provided keywords naturally
• Ready for direct insertion into Summernote editor

⸻

KEYWORD ENFORCEMENT:
You MUST include ALL these keywords naturally in the article: ${keywords.join(', ') || 'None provided, but write naturally'}
Incorporate them in relevant contexts without keyword stuffing.

IMPORTANT: Write the entire article in one continuous response. Do not break it into multiple responses.`;

    // Create a ReadableStream for streaming response
    const encoder = new TextEncoder();
    const stream = new ReadableStream({
      async start(controller) {
        try {
          // Send initial status
          controller.enqueue(encoder.encode('data: {"status": "processing", "message": "Connecting to AI service..."}\n\n'));

          // Call DeepSeek API with streaming
          const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
              'Accept': 'text/event-stream'
            },
            body: JSON.stringify({
              model: 'deepseek-chat',
              messages: [
                {
                  role: 'system',
                  content: systemPrompt
                },
                {
                  role: 'user',
                  content: userPrompt
                }
              ],
              max_tokens: 4000,
              temperature: 0.7,
              stream: true  // Enable streaming
            })
          });

          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`DeepSeek API request failed: ${response.status} ${errorText}`);
          }

          // Process streaming response
          const reader = response.body.getReader();
          let buffer = '';
          let contentStarted = false;
          
          // Send progress update
          controller.enqueue(encoder.encode('data: {"status": "processing", "message": "Generating content..."}\n\n'));

          try {
            while (true) {
              const { done, value } = await reader.read();
              
              if (done) {
                // Ensure we have closing article tag if missing
                if (contentStarted && !buffer.includes('</article>')) {
                  controller.enqueue(encoder.encode(`data: ${JSON.stringify({
                    type: 'content',
                    content: '</article>'
                  })}\n\n`));
                }
                
                // Send completion message
                controller.enqueue(encoder.encode('data: {"status": "completed", "message": "Content generation complete"}\n\n'));
                controller.close();
                break;
              }

              // Decode the chunk
              const chunk = new TextDecoder().decode(value);
              buffer += chunk;

              // Process complete SSE events
              const lines = buffer.split('\n');
              buffer = lines.pop() || ''; // Keep incomplete line in buffer

              for (const line of lines) {
                if (line.startsWith('data: ')) {
                  const data = line.slice(6);
                  
                  if (data === '[DONE]') {
                    continue;
                  }

                  if (data.trim() === '') {
                    continue;
                  }

                  try {
                    const parsed = JSON.parse(data);
                    
                    if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta && parsed.choices[0].delta.content) {
                      const content = parsed.choices[0].delta.content;
                      
                      // Check if content has started (looking for <article> tag)
                      if (!contentStarted && content.includes('<article>')) {
                        contentStarted = true;
                      }
                      
                      // Send content chunk
                      controller.enqueue(encoder.encode(`data: ${JSON.stringify({
                        type: 'content',
                        content: content
                      })}\n\n`));
                    }
                  } catch (e) {
                    console.error('Error parsing SSE data:', e, 'Data:', data);
                    // Send raw data if JSON parsing fails
                    if (data && data.trim() && data !== '[DONE]') {
                      controller.enqueue(encoder.encode(`data: ${JSON.stringify({
                        type: 'content',
                        content: data
                      })}\n\n`));
                    }
                  }
                }
              }
            }
          } finally {
            reader.releaseLock();
          }

        } catch (error) {
          console.error('Error in DeepSeek streaming:', error);
          controller.enqueue(encoder.encode(`data: ${JSON.stringify({
            status: 'error',
            error: 'Failed to generate content',
            details: error.message
          })}\n\n`));
          controller.close();
        }
      }
    });

    // Return streaming response
    return new Response(stream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no' // Disable buffering for nginx
      }
    });

  } catch (error) {
    console.error('Error in university description generation:', error);
    
    // Return regular JSON response for non-streaming errors
    return NextResponse.json(
      { 
        error: 'Failed to generate description',
        details: error.message 
      },
      { status: 500 }
    );
  }
}

// OPTIONAL: GET method to test the endpoint
export async function GET(request) {
  return NextResponse.json({
    message: 'University description generation endpoint',
    status: 'active',
    supported_methods: ['POST'],
    streaming: true
  }, { status: 200 });
}