import json
from app.ai.diamond import call_ai, _parse_json, run_sync


async def suggest_ad_targeting(report, platforms: list, budget: float, language: str = "ar") -> dict:
    """
    Use AI to analyze the feasibility report and suggest optimal ad targeting.
    Returns targeting suggestions including demographics, interests, budget split, etc.
    """
    # Build context from report data
    report_context = {
        "project_name": report.project_name,
        "project_description": report.project_description,
        "language": report.language or language,
    }
    if isinstance(report.synthesis_result, dict):
        report_context["synthesis"] = report.synthesis_result
    if isinstance(report.market_analysis, dict):
        report_context["market_analysis"] = report.market_analysis
    if isinstance(report.competitive_analysis, dict):
        report_context["competitive_analysis"] = report.competitive_analysis

    platforms_str = ", ".join(platforms)

    prompt = f"""You are an expert digital advertising strategist. Analyze the following business/feasibility report data and suggest the optimal paid ad targeting for video ad campaigns.

## Report Data:
{json.dumps(report_context, ensure_ascii=False, indent=2)}

## Campaign Parameters:
- Platforms: {platforms_str}
- Total Budget: ${budget}
- Ad Format: Video Ad

## Your Task:
Based on the report data, suggest the best targeting parameters. Return a JSON object with these exact keys:

{{
    "age_min": <int, minimum age 13-65>,
    "age_max": <int, maximum age 13-65>,
    "gender": "<all|male|female>",
    "locations": ["<ISO country codes, e.g. SA, AE, EG>"],
    "interests": ["<list of relevant interest keywords>"],
    "budget_split": {{"<platform>": <percentage as int>}},
    "recommended_duration_days": <int, 7-30>,
    "best_times": ["<HH:MM format, best posting times>"],
    "ad_caption_ar": "<suggested Arabic ad text, max 150 chars>",
    "ad_caption_en": "<suggested English ad text, max 150 chars>",
    "cta": "<LEARN_MORE|SHOP_NOW|SIGN_UP|WATCH_MORE|CONTACT_US|DOWNLOAD>",
    "ab_test_variants": [
        {{"caption": "<variant A text>", "cta": "<CTA type>"}},
        {{"caption": "<variant B text>", "cta": "<CTA type>"}}
    ],
    "warnings": ["<any warnings about budget minimums or platform restrictions>"],
    "reasoning": "<brief explanation of why these targeting choices were made>"
}}

Important rules:
- Budget split percentages must sum to 100
- Consider the target market from the report (region, demographics)
- If the report mentions a specific country/region, prioritize that in locations
- For TikTok, minimum daily budget is $20; for Meta, minimum is $1
- If budget is too low for a platform, warn about it
- Suggest interests relevant to the product/service type
- Return ONLY valid JSON, no markdown formatting"""

    messages = [{"role": "user", "content": prompt}]

    try:
        response = await call_ai(messages, model_type="fast")
        suggestions = _parse_json(response)

        if not isinstance(suggestions, dict) or "raw_text" in suggestions:
            return _default_suggestions(platforms, budget)

        # Validate and fill defaults
        suggestions.setdefault("age_min", 18)
        suggestions.setdefault("age_max", 45)
        suggestions.setdefault("gender", "all")
        suggestions.setdefault("locations", ["SA"])
        suggestions.setdefault("interests", [])
        suggestions.setdefault("recommended_duration_days", 7)
        suggestions.setdefault("cta", "LEARN_MORE")
        suggestions.setdefault("warnings", [])

        # Ensure budget_split exists and sums to 100
        if "budget_split" not in suggestions or not isinstance(suggestions["budget_split"], dict):
            equal_split = 100 // len(platforms)
            suggestions["budget_split"] = {p: equal_split for p in platforms}
            remainder = 100 - (equal_split * len(platforms))
            if remainder > 0:
                suggestions["budget_split"][platforms[0]] += remainder

        # Add budget warnings
        daily_budget = budget / suggestions.get("recommended_duration_days", 7)
        for platform in platforms:
            pct = suggestions["budget_split"].get(platform, 0)
            platform_daily = daily_budget * (pct / 100)
            if platform == "tiktok" and platform_daily < 20:
                suggestions["warnings"].append(
                    f"TikTok minimum daily budget is $20. Current allocation: ${platform_daily:.2f}/day. Consider increasing budget or removing TikTok."
                )
            if platform in ("facebook", "instagram") and platform_daily < 1:
                suggestions["warnings"].append(
                    f"Meta minimum daily budget is $1. Current allocation: ${platform_daily:.2f}/day."
                )

        return suggestions

    except Exception as e:
        return _default_suggestions(platforms, budget, error=str(e))


def suggest_targeting_sync(report, platforms: list, budget: float, language: str = "ar") -> dict:
    """Synchronous wrapper for suggest_ad_targeting."""
    return run_sync(suggest_ad_targeting(report, platforms, budget, language))


def _default_suggestions(platforms: list, budget: float, error: str = None) -> dict:
    """Return sensible defaults if AI fails."""
    equal_split = 100 // max(len(platforms), 1)
    budget_split = {p: equal_split for p in platforms}
    if platforms:
        remainder = 100 - (equal_split * len(platforms))
        budget_split[platforms[0]] += remainder

    result = {
        "age_min": 18,
        "age_max": 45,
        "gender": "all",
        "locations": ["SA"],
        "interests": [],
        "budget_split": budget_split,
        "recommended_duration_days": 7,
        "best_times": ["12:00", "18:00", "21:00"],
        "ad_caption_ar": "",
        "ad_caption_en": "",
        "cta": "LEARN_MORE",
        "ab_test_variants": [],
        "warnings": [],
        "reasoning": "Default targeting (AI suggestion unavailable)",
    }
    if error:
        result["warnings"].append(f"AI targeting failed: {error}. Using defaults.")
    return result
