import os
from google import genai


def generate_explanation(
    risk_score,
    verdict,
    contributing_features
):
    api_key = os.getenv("GEMINI_API_KEY")

    if not api_key:
        return "AI explanation unavailable."

    try:
        client = genai.Client(api_key=api_key)

        prompt = f"""
You are an ad-tech Invalid Traffic (IVT) analysis assistant.

Explain the following IVT validation result in 1-2 short sentences.

Risk Score: {risk_score}
Verdict: {verdict}
Contributing Features: {contributing_features}

Important:
- Do not change or recalculate the risk score.
- Do not change the verdict.
- Only explain why the traffic was classified this way.
- Keep the explanation simple and technical.
"""

        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=prompt
        )

        return response.text.strip()

    except Exception as e:
        print(f"AI explanation error: {e}")
        return "AI explanation unavailable."
