"""
ai_explainer.py
Uses Google Gemini (free API from Google AI Studio) to explain the audit
results in plain, easy-to-understand English, acting as a "growth marketing
consultant" -- not searching for new data, just explaining data that has
already been extracted and scored by the Rule Engine.

If GEMINI_API_KEY is not set, this module automatically falls back to a
template-based summary (still fully functional and free, no API key needed).
"""
import os
import json
import httpx

GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.0-flash")
GEMINI_URL = (
    f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent"
)


def _fallback_summary(url: str, growth_score: int, top_recs: list[dict]) -> str:
    lines = [
        f"The Growth Score for {url} is {growth_score}/100.",
        "Here are a few of the highest-impact things to fix first:",
    ]
    for r in top_recs[:3]:
        lines.append(f"- {r['title']}: {r['why_it_matters']}")
    lines.append(
        "Start with recommendations labeled 'quick win' -- they're high impact but easy to implement."
    )
    return "\n".join(lines)


async def generate_explanation(url: str, growth_score: int, category_breakdown: list[dict],
                                top_recommendations: list[dict]) -> str:
    if not GEMINI_API_KEY:
        return _fallback_summary(url, growth_score, top_recommendations)

    weak_categories = [c for c in category_breakdown if c["score"] < 70]
    prompt = f"""
You are a growth marketing consultant. Explain the following website audit
results in friendly, concise English (max 150 words) that a small business
owner with no technical background can easily understand.
Do not repeat raw numbers -- focus on insight and concrete next steps.
Respond only in English, regardless of the language of the input data below.

URL: {url}
Growth Score: {growth_score}/100
Weak categories: {json.dumps([c['label'] for c in weak_categories], ensure_ascii=False)}
Top priority recommendations: {json.dumps([r['title'] for r in top_recommendations[:5]], ensure_ascii=False)}
"""

    payload = {"contents": [{"parts": [{"text": prompt}]}]}
    try:
        async with httpx.AsyncClient(timeout=20.0) as client:
            resp = await client.post(
                f"{GEMINI_URL}?key={GEMINI_API_KEY}",
                json=payload,
                headers={"Content-Type": "application/json"},
            )
        if resp.status_code != 200:
            return _fallback_summary(url, growth_score, top_recommendations)
        data = resp.json()
        text = data["candidates"][0]["content"]["parts"][0]["text"]
        return text.strip()
    except Exception:
        return _fallback_summary(url, growth_score, top_recommendations)
