from __future__ import annotations

import json
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from ..config import ClientConfig, client_dir
from ..google_ads import get_google_ads_client, run_query
from ..history import append_change_markdown, append_history, now_local
from ..knowledge.store import rules_for_task
from ..table import print_table


TASK_ID = "check_pmax_structure"
TASK_NAME = "Sprawdzenie struktury PMax"


SCOPE = [
    {
        "area": "Kampanie PMax",
        "check": "Pokaz aktywne i wstrzymane kampanie Performance Max oraz ich podstawowe wyniki z ostatnich 30 dni.",
    },
    {
        "area": "Asset groups",
        "check": "Policz asset groups w kazdej kampanii i wskaz kampanie wymagajace recznej oceny struktury.",
    },
    {
        "area": "Feed produktowy",
        "check": "Oznacz, ze ocena feedu produktowego jest polaczona z osobnym zadaniem Feed i Merchant Center.",
    },
    {
        "area": "Brand / non-brand",
        "check": "Wskaz kampanie, ktore po nazwie moga wymagac recznej oceny podzialu brand/non-brand.",
    },
    {
        "area": "Kanibalizacja",
        "check": "Wypisz ryzyko kanibalizacji Search, Shopping i remarketingu jako punkt do recznej oceny.",
    },
]


OUT_OF_SCOPE = [
    "budzety i pacing budzetu",
    "strategie stawek oraz cele Docelowy ROAS/Docelowy CPA",
    "zapytania uzytkownikow oraz wykluczenia",
    "reklamy RSA i zasoby Search",
    "wdrazanie zmian w kampaniach Performance Max",
]


@dataclass
class PmaxStructurePlan:
    currency_code: str
    campaigns: list[dict]
    asset_groups: list[dict]
    scope: list[dict]
    out_of_scope: list[str]
    knowledge_rules: list[dict]
    warnings: list[str]

    def to_dict(self) -> dict:
        return {
            "task": TASK_ID,
            "task_name": TASK_NAME,
            "currency_code": self.currency_code,
            "campaigns": self.campaigns,
            "asset_groups": self.asset_groups,
            "scope": self.scope,
            "out_of_scope": self.out_of_scope,
            "knowledge_rules": self.knowledge_rules,
            "warnings": self.warnings,
            "changes": [],
        }

    @classmethod
    def from_dict(cls, data: dict) -> "PmaxStructurePlan":
        return cls(
            currency_code=data.get("currency_code", ""),
            campaigns=data.get("campaigns", []),
            asset_groups=data.get("asset_groups", []),
            scope=data.get("scope", []),
            out_of_scope=data.get("out_of_scope", []),
            knowledge_rules=data.get("knowledge_rules", []),
            warnings=data.get("warnings", []),
        )


def enum_name(value: Any) -> str:
    name = getattr(value, "name", None)
    if name:
        return name
    return str(value)


def safe_int(value: Any) -> int:
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def safe_float(value: Any) -> float:
    try:
        return float(value or 0)
    except (TypeError, ValueError):
        return 0.0


def micros_to_amount(value: int | float) -> float:
    return round(float(value or 0) / 1_000_000, 2)


def format_money(value: int | float, currency_code: str) -> str:
    suffix = f" {currency_code}" if currency_code else ""
    return f"{micros_to_amount(value):.2f}{suffix}"


def format_decimal(value: int | float) -> str:
    return f"{float(value or 0):.2f}"


def md_cell(value: Any) -> str:
    return str(value or "").replace("|", "\\|").replace("\n", " ").strip()


def pmax_risks(campaign_name: str, asset_group_count: int, conversions_30d: float) -> list[str]:
    name = campaign_name.casefold()
    risks = []
    if asset_group_count == 0:
        risks.append("brak asset groups")
    if asset_group_count == 1:
        risks.append("jedna asset group")
    if any(token in name for token in ["brand", "branded", "marka"]):
        risks.append("sprawdz brand/non-brand")
    if conversions_30d <= 0:
        risks.append("brak konwersji w 30 dni")
    risks.append("sprawdz kanibalizacje Search/Shopping")
    return risks


def fetch_currency_code(google_client, customer_id: str) -> str:
    rows = run_query(
        google_client,
        customer_id,
        """
        SELECT
          customer.currency_code
        FROM customer
        """,
    )
    if not rows:
        return ""
    return str(rows[0].customer.currency_code or "")


def fetch_pmax_asset_groups(google_client, customer_id: str, warnings: list[str]) -> list[dict]:
    try:
        rows = run_query(
            google_client,
            customer_id,
            """
            SELECT
              campaign.id,
              campaign.name,
              asset_group.id,
              asset_group.name,
              asset_group.status
            FROM asset_group
            WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
              AND campaign.status != 'REMOVED'
              AND asset_group.status != 'REMOVED'
            """,
        )
    except Exception as exc:
        warnings.append(f"Nie udalo sie pobrac asset groups PMax: {exc}")
        return []

    asset_groups = []
    for row in rows:
        asset_groups.append(
            {
                "campaign_id": str(row.campaign.id),
                "campaign_name": row.campaign.name,
                "asset_group_id": str(row.asset_group.id),
                "asset_group_name": row.asset_group.name,
                "status": enum_name(row.asset_group.status),
            }
        )
    return asset_groups


def fetch_pmax_campaigns(client_config: ClientConfig) -> tuple[str, list[dict], list[dict], list[str]]:
    warnings: list[str] = []
    google_client = get_google_ads_client(use_proto_plus=True)
    customer_id = client_config.safe_customer_id
    currency_code = fetch_currency_code(google_client, customer_id)
    asset_groups = fetch_pmax_asset_groups(google_client, customer_id, warnings)
    asset_groups_by_campaign: dict[str, list[dict]] = defaultdict(list)
    for asset_group in asset_groups:
        asset_groups_by_campaign[asset_group["campaign_id"]].append(asset_group)

    rows = run_query(
        google_client,
        customer_id,
        """
        SELECT
          campaign.id,
          campaign.name,
          campaign.status,
          campaign.advertising_channel_type,
          campaign.bidding_strategy_type,
          metrics.cost_micros,
          metrics.conversions,
          metrics.conversions_value
        FROM campaign
        WHERE campaign.advertising_channel_type = 'PERFORMANCE_MAX'
          AND campaign.status != 'REMOVED'
          AND segments.date DURING LAST_30_DAYS
        """,
    )

    campaigns = []
    for row in rows:
        campaign_id = str(row.campaign.id)
        asset_group_count = len(asset_groups_by_campaign.get(campaign_id, []))
        conversions_30d = safe_float(row.metrics.conversions)
        campaigns.append(
            {
                "campaign_id": campaign_id,
                "campaign_name": row.campaign.name,
                "status": enum_name(row.campaign.status),
                "channel_type": enum_name(row.campaign.advertising_channel_type),
                "bidding_strategy_type": enum_name(row.campaign.bidding_strategy_type),
                "cost_30d_micros": safe_int(row.metrics.cost_micros),
                "conversions_30d": conversions_30d,
                "conversion_value_30d": safe_float(row.metrics.conversions_value),
                "asset_group_count": asset_group_count,
                "risk_labels": pmax_risks(row.campaign.name, asset_group_count, conversions_30d),
            }
        )
    return currency_code, campaigns, asset_groups, warnings


def build_pmax_structure_plan(client_config: ClientConfig) -> PmaxStructurePlan:
    warnings = []
    try:
        currency_code, campaigns, asset_groups, fetch_warnings = fetch_pmax_campaigns(client_config)
        warnings.extend(fetch_warnings)
    except Exception as exc:
        currency_code = ""
        campaigns = []
        asset_groups = []
        warnings.append(f"Nie udalo sie pobrac kampanii Performance Max z Google Ads API: {exc}")

    if not campaigns:
        warnings.append("Nie znaleziono kampanii Performance Max z danymi z ostatnich 30 dni albo nie udalo sie ich pobrac.")

    warnings.append(
        "Informacje o feedzie produktowym i problemach produktow sprawdzaj w osobnym zadaniu Feed i Merchant Center."
    )
    warnings.append(
        "Kanibalizacja Search/Shopping/remarketing wymaga recznej oceny z innymi zadaniami, a nie automatycznej decyzji."
    )

    knowledge_rules = [
        {
            "id": rule.id,
            "topic": rule.topic,
            "rule_type": rule.rule_type,
            "condition": rule.condition,
            "recommendation": rule.recommendation,
            "risk": rule.risk,
            "source": rule.source,
        }
        for rule in rules_for_task(TASK_ID)
    ]
    if not knowledge_rules:
        warnings.append(
            "Do tego zadania nie przypisano jeszcze regul z bazy wiedzy. "
            "Reguly dotyczace Performance Max bedziemy dopisywac osobno po akceptacji uzytkownika."
        )

    campaigns.sort(key=lambda row: (row["status"], row["campaign_name"]))
    return PmaxStructurePlan(
        currency_code=currency_code,
        campaigns=campaigns,
        asset_groups=asset_groups,
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_pmax_structure_plan(domain: str, plan: PmaxStructurePlan) -> tuple[Path, Path]:
    ts = now_local()
    base = client_dir(domain) / "plans"
    base.mkdir(parents=True, exist_ok=True)
    stem = f"{ts.strftime('%Y-%m-%d_%H-%M-%S')}_{TASK_ID}"
    json_path = base / f"{stem}.json"
    md_path = base / f"{stem}.md"
    payload = {
        "created_at": ts.isoformat(timespec="seconds"),
        "client": domain,
        **plan.to_dict(),
    }
    json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")

    lines = [
        "# Plan: Sprawdzenie struktury PMax",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Kampanie PMax: {len(plan.campaigns)}",
        f"- Asset groups: {len(plan.asset_groups)}",
        f"- Reguly wiedzy przypisane do zadania: {len(plan.knowledge_rules)}",
        "- Zmiany do wdrozenia: 0",
        "",
    ]
    if plan.warnings:
        lines.extend(["## Uwagi", ""])
        lines.extend(f"- {item}" for item in plan.warnings)
        lines.append("")
    lines.extend(["## Zakres zadania", "", "| Obszar | Co sprawdzic |", "| --- | --- |"])
    for row in plan.scope:
        lines.append(f"| {md_cell(row.get('area', ''))} | {md_cell(row.get('check', ''))} |")
    lines.append("")
    lines.extend(["## Poza zakresem tego zadania", ""])
    lines.extend(f"- {item}" for item in plan.out_of_scope)
    lines.append("")
    if plan.campaigns:
        lines.extend(
            [
                "## Kampanie Performance Max",
                "",
                "| Kampania | Status | Asset groups | Koszt 30 dni | Konwersje | Wartosc konwersji | Ryzyka |",
                "| --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for campaign in plan.campaigns:
            lines.append(
                f"| {md_cell(campaign['campaign_name'])} | {campaign['status']} | "
                f"{campaign['asset_group_count']} | {format_money(campaign['cost_30d_micros'], plan.currency_code)} | "
                f"{format_decimal(campaign['conversions_30d'])} | {format_decimal(campaign['conversion_value_30d'])} | "
                f"{md_cell(', '.join(campaign['risk_labels']))} |"
            )
        lines.append("")
    if plan.asset_groups:
        lines.extend(
            [
                "## Asset groups",
                "",
                "| Kampania | Asset group | Status |",
                "| --- | --- | --- |",
            ]
        )
        for asset_group in plan.asset_groups:
            lines.append(
                f"| {md_cell(asset_group['campaign_name'])} | "
                f"{md_cell(asset_group['asset_group_name'])} | {asset_group['status']} |"
            )
        lines.append("")
    if plan.knowledge_rules:
        lines.extend(
            [
                "## Reguly z bazy wiedzy",
                "",
                "| ID | Temat | Rekomendacja | Ryzyko |",
                "| --- | --- | --- | --- |",
            ]
        )
        for rule in plan.knowledge_rules:
            lines.append(
                f"| {md_cell(rule.get('id', ''))} | {md_cell(rule.get('topic', ''))} | "
                f"{md_cell(rule.get('recommendation', ''))} | {md_cell(rule.get('risk', ''))} |"
            )
        lines.append("")
    md_path.write_text("\n".join(lines), encoding="utf-8")
    return json_path, md_path


def print_pmax_structure_plan(plan: PmaxStructurePlan) -> None:
    print("\nPlan sprawdzenia struktury PMax")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Kampanie PMax", str(len(plan.campaigns))],
            ["Asset groups", str(len(plan.asset_groups))],
            ["Reguly wiedzy", str(len(plan.knowledge_rules))],
            ["Zmiany do wdrozenia", "0"],
        ],
    )
    if plan.warnings:
        print("\nUwagi")
        print_table(["Nr", "Uwaga"], [[str(index), item] for index, item in enumerate(plan.warnings, 1)])
    print("\nZakres zadania")
    print_table(
        ["Nr", "Obszar", "Co sprawdzic"],
        [[str(index), row["area"], row["check"]] for index, row in enumerate(plan.scope, 1)],
    )
    print("\nPoza zakresem")
    print_table(["Nr", "Nie analizujemy tutaj"], [[str(index), item] for index, item in enumerate(plan.out_of_scope, 1)])
    if plan.campaigns:
        print("\nKampanie Performance Max")
        print_table(
            ["Nr", "Kampania", "Status", "Asset groups", "Koszt 30 dni", "Konw.", "Ryzyka"],
            [
                [
                    str(index),
                    campaign["campaign_name"],
                    campaign["status"],
                    str(campaign["asset_group_count"]),
                    format_money(campaign["cost_30d_micros"], plan.currency_code),
                    format_decimal(campaign["conversions_30d"]),
                    ", ".join(campaign["risk_labels"]),
                ]
                for index, campaign in enumerate(plan.campaigns, 1)
            ],
        )
    if plan.asset_groups:
        print("\nAsset groups")
        print_table(
            ["Nr", "Kampania", "Asset group", "Status"],
            [
                [str(index), row["campaign_name"], row["asset_group_name"], row["status"]]
                for index, row in enumerate(plan.asset_groups[:30], 1)
            ],
        )
        if len(plan.asset_groups) > 30:
            print(f"... oraz {len(plan.asset_groups) - 30} kolejnych asset groups w pliku planu")
    if plan.knowledge_rules:
        print("\nReguly z bazy wiedzy")
        print_table(
            ["Nr", "ID", "Temat", "Rekomendacja"],
            [
                [str(index), rule["id"], rule["topic"], rule["recommendation"]]
                for index, rule in enumerate(plan.knowledge_rules[:10], 1)
            ],
        )
        if len(plan.knowledge_rules) > 10:
            print(f"... oraz {len(plan.knowledge_rules) - 10} kolejnych regul")


def print_next_navigation(domain: str) -> None:
    print("\nCo dalej:")
    print(f"1. Lista zadan klienta {domain}")
    print("2. Lista klientow")
    print("3. Zakoncz")
    print("\nKomendy:")
    print(f"1 -> python gads.py analiza-klienta --client {domain}")
    print("2 -> python gads.py analiza-klienta")


def apply_pmax_structure_plan(
    client_config: ClientConfig,
    plan: PmaxStructurePlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem struktury PMax i nie wdraza zmian na koncie Google Ads.")
    changes_path = append_change_markdown(client_config.domain, TASK_NAME, [])
    history_path = append_history(
        client_config.domain,
        {
            "task": TASK_NAME,
            "status": "audyt oznaczony jako wykonany",
            "campaign": ", ".join(campaign["campaign_name"] for campaign in plan.campaigns[:10]),
            "summary": {
                "campaigns": len(plan.campaigns),
                "asset_groups": len(plan.asset_groups),
                "knowledge_rules": len(plan.knowledge_rules),
                "changes": 0,
            },
        },
    )
    print(f"Historia JSONL: {history_path}")
    print(f"Historia Markdown: {changes_path}")
    if show_navigation:
        print_next_navigation(client_config.domain)


def run_check_pmax_structure(
    client_config: ClientConfig,
    global_rules: dict,
    plan_only: bool = False,
    apply_plan_path: str | None = None,
    confirm_apply: str | None = None,
    show_navigation: bool = True,
) -> None:
    _ = global_rules
    if apply_plan_path:
        if confirm_apply != "TAK":
            print("Do oznaczenia audytu jako wykonanego wymagane jest --confirm-apply TAK.")
            if show_navigation:
                print_next_navigation(client_config.domain)
            return
        plan_data = json.loads(Path(apply_plan_path).read_text(encoding="utf-8"))
        if plan_data.get("client") != client_config.domain:
            print(f"Plan jest dla klienta {plan_data.get('client')}, a wybrano {client_config.domain}.")
            if show_navigation:
                print_next_navigation(client_config.domain)
            return
        plan = PmaxStructurePlan.from_dict(plan_data)
        print_pmax_structure_plan(plan)
        apply_pmax_structure_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia struktury PMax...")
    plan = build_pmax_structure_plan(client_config)
    print_pmax_structure_plan(plan)
    json_path, md_path = save_pmax_structure_plan(client_config.domain, plan)
    print(f"\nPlan JSON: {json_path}")
    print(f"Plan Markdown: {md_path}")

    append_history(
        client_config.domain,
        {
            "task": TASK_NAME,
            "status": "plan przygotowany",
            "campaign": ", ".join(campaign["campaign_name"] for campaign in plan.campaigns[:10]),
            "summary": {
                "campaigns": len(plan.campaigns),
                "asset_groups": len(plan.asset_groups),
                "knowledge_rules": len(plan.knowledge_rules),
                "changes": 0,
            },
        },
    )

    if plan_only:
        print("\nTryb plan-only: zmiany nie zostaly wdrozone.")
        if show_navigation:
            print_next_navigation(client_config.domain)
        return

    print("\nBrak zmian do wdrozenia. To zadanie tworzy plan audytu struktury PMax.")
    if show_navigation:
        print_next_navigation(client_config.domain)
