import json
import re
import logging

logger = logging.getLogger(__name__)


class GeminiWriter:
    """Generate blog content using Google Gemini AI (FREE tier)."""

    def __init__(self, api_key):
        import google.generativeai as genai

        genai.configure(api_key=api_key)
        self.model = genai.GenerativeModel("gemini-2.5-flash")

    # ------------------------------------------------------------------
    def generate_blog_post(self, keyword, tone="professional", word_count=2000, style="technical"):
        """Generate a full SEO-optimised blog post."""

        prompt = f"""You are an expert SEO content writer for a popular IT and technology blog.

Write a comprehensive, SEO-optimised blog post about: **{keyword}**

REQUIREMENTS:
- Word count: approximately {word_count} words
- Tone: {tone}
- Style: {style}, reader-friendly, with tables and practical examples
- Include proper HTML formatting (h2, h3, p, ul, ol, table, code blocks where relevant)
- DO NOT include h1 tag (the title will be added separately)
- Include internal linking suggestions as [INTERNAL_LINK: topic] placeholders
- Make it engaging with a strong introduction and conclusion
- Include practical, actionable advice
- Use bullet points and numbered lists where appropriate
- Include a comparison table if the topic allows it

RETURN your response as valid JSON with exactly these fields:
{{
    "title": "SEO-optimised title (50-60 characters ideal)",
    "slug": "url-friendly-slug",
    "meta_description": "Compelling meta description under 155 characters",
    "content_html": "The full blog post in HTML format",
    "tags": ["tag1", "tag2", "tag3", "tag4", "tag5"],
    "category": "Most appropriate single category name",
    "faq": [
        {{"question": "FAQ question 1?", "answer": "Detailed answer 1"}},
        {{"question": "FAQ question 2?", "answer": "Detailed answer 2"}},
        {{"question": "FAQ question 3?", "answer": "Detailed answer 3"}},
        {{"question": "FAQ question 4?", "answer": "Detailed answer 4"}}
    ]
}}

IMPORTANT: Return ONLY valid JSON. No markdown code fences. No extra text."""

        try:
            response = self.model.generate_content(prompt)
            raw_text = response.text.strip()

            # Clean up markdown code fences if present
            if raw_text.startswith("```"):
                raw_text = re.sub(r"^```(?:json)?\n?", "", raw_text)
                raw_text = re.sub(r"\n?```$", "", raw_text)

            result = json.loads(raw_text)

            # Add FAQ as HTML to content
            if result.get("faq"):
                faq_html = "\n<h2>Frequently Asked Questions</h2>\n"
                for item in result["faq"]:
                    faq_html += f'''<div class="faq-item">
<h3>{item["question"]}</h3>
<p>{item["answer"]}</p>
</div>\n'''
                result["content_html"] += faq_html

            return result

        except json.JSONDecodeError as e:
            logger.error(f"Failed to parse Gemini response as JSON: {e}")
            # Try to extract useful content anyway
            return {
                "title": keyword.title(),
                "slug": keyword.lower().replace(" ", "-"),
                "meta_description": f"Learn about {keyword}",
                "content_html": f"<p>{raw_text}</p>",
                "tags": [keyword],
                "category": "General",
                "faq": [],
                "parse_error": str(e),
            }
        except Exception as e:
            logger.error(f"Gemini generation failed: {e}")
            raise Exception(f"AI generation failed: {e}")

    # ------------------------------------------------------------------
    def generate_meta_description(self, title, content):
        """Generate an SEO meta description."""
        prompt = f"""Write a compelling SEO meta description (under 155 characters) for this blog post.
Title: {title}
Content summary: {content[:500]}
Return ONLY the meta description text, nothing else."""

        try:
            response = self.model.generate_content(prompt)
            return response.text.strip()[:155]
        except Exception as e:
            logger.error(f"Meta generation failed: {e}")
            return ""

    # ------------------------------------------------------------------
    def suggest_keywords(self, topic):
        """Suggest related keywords for a topic."""
        prompt = f"""Suggest 15 related SEO keywords/phrases for the topic: "{topic}"

For each keyword, include:
- The keyword phrase
- Search intent (informational, commercial, navigational, transactional)
- Estimated difficulty (low, medium, high)

Return as valid JSON array:
[
    {{"keyword": "example keyword", "intent": "informational", "difficulty": "low"}},
    ...
]

Return ONLY valid JSON. No extra text."""

        try:
            response = self.model.generate_content(prompt)
            raw = response.text.strip()
            if raw.startswith("```"):
                raw = re.sub(r"^```(?:json)?\n?", "", raw)
                raw = re.sub(r"\n?```$", "", raw)
            return json.loads(raw)
        except Exception as e:
            logger.error(f"Keyword suggestion failed: {e}")
            return []

    # ------------------------------------------------------------------
    def analyze_content_seo(self, content_html):
        """Analyse content for SEO quality."""
        prompt = f"""Analyse this blog post HTML for SEO quality. Score it 0-100.

Content:
{content_html[:3000]}

Return as valid JSON:
{{
    "score": 85,
    "issues": ["issue 1", "issue 2"],
    "suggestions": ["suggestion 1", "suggestion 2"],
    "keyword_density": "2.1%",
    "readability": "Good"
}}

Return ONLY valid JSON."""

        try:
            response = self.model.generate_content(prompt)
            raw = response.text.strip()
            if raw.startswith("```"):
                raw = re.sub(r"^```(?:json)?\n?", "", raw)
                raw = re.sub(r"\n?```$", "", raw)
            return json.loads(raw)
        except Exception as e:
            logger.error(f"SEO analysis failed: {e}")
            return {"score": 0, "issues": [str(e)], "suggestions": []}
