from google import genai
from config import GEMINI_API_KEY
import time

client = genai.Client(api_key=GEMINI_API_KEY)


def analyze_campaign(data):
    prompt = f"""
    Analyze this ad campaign performance.

    Campaign Name: {data['campaignname']}
    Impressions: {data['impressions']}
    Clicks: {data['clicks']}
    CTR: {data['ctr']}%

    Provide:
    1. Performance summary
    2. Problems identified
    3. Optimization suggestions
    4. Budget efficiency analysis
    5. Audience targeting recommendations
    6. Creative improvement suggestions.

    Keep the response professional and concise.
    """

    models = [
        "gemini-2.5-flash",
        "gemini-2.0-flash"
    ]

    for model_name in models:
        for attempt in range(3):
            try:
                response = client.models.generate_content(
                    model=model_name,
                    contents=prompt
                )
                return response.text

            except Exception as e:
                print(f"{model_name} attempt {attempt + 1} failed: {e}")
                time.sleep(5)

    return "Gemini service is temporarily unavailable. Please try again later."