import os
import requests
import json
from django.utils.text import slugify

# ==========================================
# 📊 CountryBLOG GROQ
# ==========================================   
    
def generate_country_guide_ai(country_name):
    """
    Version 9.0: Natural & Informative Branding Logic.
    Focuses on user value while weaving in Videsh Chalo subtly for trust.
    Includes Currency Comparison section.
    """
    api_key = os.environ.get('GROQ_API_KEY')
    if not api_key:
        print("Groq API Key missing.")
        return None

    # 🎯 Natural SEO Keywords
    keywords = f"jobs in {country_name}, Indian workers in {country_name}, {country_name} work visa, {country_name} salary in INR, videsh chalo {country_name} guide"

    prompt = f"""
    SYSTEM INSTRUCTION: You are an Expert International Career Consultant for Indian Workers. 
    Your goal is to provide a highly informative, educational, and helpful guide for '{country_name}'. 
    DO NOT sound like an advertisement. Branding for 'Videsh Chalo' must be subtle and woven into the advice naturally.

    TASK: Write a 1000-word professional HTML guide for Indian candidates.

    **CONTENT & STRUCTURE RULES:**
    1.  **Tone:** Knowledgeable, friendly, and objective. Information must come first.
    2.  **Introduction:** Start with a warm introduction to {country_name}. Mention why Indians prefer it.
    3.  **Branding (Subtle):** Mention 'Videsh Chalo' (www.videshchalo.com) only when giving advice. 
        * Example: "When applying for {country_name} jobs, we at Videsh Chalo recommend checking..." 
        * Example: "Videsh Chalo's team often sees that candidates with..."
    4.  **Currency Section (MANDATORY):** Include a section "<h3>Money Matters: {country_name} Currency vs INR</h3>". 
        Explain the local currency name, its current approximate value compared to the Indian Rupee (INR), and the purchasing power for a worker (savings potential).
    5.  **Our Services (Natural):** Instead of a dedicated sales section, mention that Videsh Chalo helps with profile auditing, connecting with verified recruiters, and visa documentation in the context of "How to get started".
    6.  **Keywords:** Use these phrases naturally: {keywords}.
    7.  **Formatting:** Use STRICT HTML (<h2>, <h3>, <p>, <ul>, <li>, <strong>). No Markdown.

    **SECTION GUIDELINE:**
    - [Intro] About {country_name} and its geography/vibe.
    - [Employment Landscape] Demand for construction, hospitality, or technical trades.
    - [Currency & Finance] Comparison with INR and savings potential.
    - [Living & Culture] Local language support (Hindi/English), food, and social life.
    - [The Application Process] How to prepare. Mention how Videsh Chalo assists with interview arrangements and visa papers.
    - [Pros & Cons] Honest assessment for Indian workers.
    """

    url = "https://api.groq.com/openai/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": "llama-3.3-70b-versatile",
        "messages": [
            {"role": "system", "content": "You are a professional travel and career guide. You provide valuable info first and promote the brand 'Videsh Chalo' only where it adds value to the reader."},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.6,
        "max_tokens": 2500
    }

    try:
        print(f"Generating NATURAL AI Guide for: {country_name}...")
        response = requests.post(url, headers=headers, json=payload, timeout=60)
        
        if response.status_code != 200:
            return None
            
        result = response.json()
        content = result['choices'][0]['message']['content']
        
        # Basic cleanup
        content = content.replace("```html", "").replace("```", "").strip()
        return content
        
    except Exception as e:
        print(f"Natural AI Gen Error: {e}")
        return None