from __future__ import annotations

import json
from collections import Counter
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_impression_share"
TASK_NAME = "Sprawdzenie udzialu w wyswietleniach"


SCOPE = [
    {
        "area": "Udzial w wyswietleniach",
        "check": "Sprawdz search impression share dla kampanii z ostatnich 30 dni.",
    },
    {
        "area": "Utrata przez budzet",
        "check": "Oznacz kampanie z istotna utrata udzialu w wyswietleniach przez budzet.",
    },
    {
        "area": "Utrata przez ranking",
        "check": "Oznacz kampanie z istotna utrata udzialu w wyswietleniach przez ranking.",
    },
    {
        "area": "Widocznosc top",
        "check": "Pokaz top impression share i absolute top impression share jako sygnal konkurencyjnosci.",
    },
]


OUT_OF_SCOPE = [
    "zmiany budzetow",
    "zmiany stawek i strategii ustalania stawek",
    "decyzje o zmianie Docelowego ROAS albo Docelowego CPA",
    "analiza zapytan uzytkownikow",
    "wdrazanie zmian na koncie Google Ads",
]


@dataclass
class ImpressionSharePlan:
    campaigns: list[dict]
    channel_summary: list[dict]
    problem_items: 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,
            "campaigns": self.campaigns,
            "channel_summary": self.channel_summary,
            "problem_items": self.problem_items,
            "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) -> "ImpressionSharePlan":
        return cls(
            campaigns=data.get("campaigns", []),
            channel_summary=data.get("channel_summary", []),
            problem_items=data.get("problem_items", []),
            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 md_cell(value: Any) -> str:
    return str(value or "").replace("|", "\\|").replace("\n", " ").strip()


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 percent(value: float | int | None) -> float:
    if value is None:
        return 0.0
    return round(float(value or 0) * 100, 1)


def percent_label(value: float | int | None) -> str:
    return f"{percent(value):.1f}%"


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 issue_severity(row: dict) -> str:
    if row["search_budget_lost_impression_share"] >= 0.3:
        return "wysokie"
    if row["search_rank_lost_impression_share"] >= 0.5:
        return "wysokie"
    if row["search_budget_lost_impression_share"] >= 0.15:
        return "srednie"
    if row["search_rank_lost_impression_share"] >= 0.3:
        return "srednie"
    if row["search_impression_share"] and row["search_impression_share"] < 0.2:
        return "niskie"
    return "ok"


def campaign_flags(row: dict) -> list[str]:
    flags = []
    if row["search_budget_lost_impression_share"] >= 0.3:
        flags.append("duza utrata przez budzet")
    elif row["search_budget_lost_impression_share"] >= 0.15:
        flags.append("utrata przez budzet do oceny")
    if row["search_rank_lost_impression_share"] >= 0.5:
        flags.append("duza utrata przez ranking")
    elif row["search_rank_lost_impression_share"] >= 0.3:
        flags.append("utrata przez ranking do oceny")
    if row["search_impression_share"] and row["search_impression_share"] < 0.2:
        flags.append("niski udzial w wyswietleniach")
    if row["impressions"] == 0:
        flags.append("brak wyswietlen 30 dni")
    return flags or ["ok"]


def fetch_impression_share_campaigns(client_config: ClientConfig) -> tuple[str, list[dict]]:
    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)
    rows = run_query(
        google_client,
        customer_id,
        """
        SELECT
          campaign.id,
          campaign.name,
          campaign.status,
          campaign.advertising_channel_type,
          metrics.impressions,
          metrics.clicks,
          metrics.cost_micros,
          metrics.conversions,
          metrics.conversions_value,
          metrics.search_impression_share,
          metrics.search_budget_lost_impression_share,
          metrics.search_rank_lost_impression_share,
          metrics.search_top_impression_share,
          metrics.search_absolute_top_impression_share
        FROM campaign
        WHERE campaign.status != 'REMOVED'
          AND segments.date DURING LAST_30_DAYS
        """,
    )

    campaigns = []
    for row in rows:
        metrics = row.metrics
        record = {
            "campaign_id": str(row.campaign.id),
            "campaign_name": row.campaign.name,
            "status": enum_name(row.campaign.status),
            "channel_type": enum_name(row.campaign.advertising_channel_type),
            "impressions": int(metrics.impressions or 0),
            "clicks": int(metrics.clicks or 0),
            "cost_micros": int(metrics.cost_micros or 0),
            "cost": format_money(metrics.cost_micros, currency_code),
            "conversions": round(float(metrics.conversions or 0), 2),
            "conversion_value": round(float(metrics.conversions_value or 0), 2),
            "search_impression_share": float(metrics.search_impression_share or 0),
            "search_budget_lost_impression_share": float(metrics.search_budget_lost_impression_share or 0),
            "search_rank_lost_impression_share": float(metrics.search_rank_lost_impression_share or 0),
            "search_top_impression_share": float(metrics.search_top_impression_share or 0),
            "search_absolute_top_impression_share": float(metrics.search_absolute_top_impression_share or 0),
        }
        record["severity"] = issue_severity(record)
        record["flags"] = campaign_flags(record)
        campaigns.append(record)

    severity_order = {"wysokie": 0, "srednie": 1, "niskie": 2, "ok": 9}
    campaigns.sort(
        key=lambda row: (
            severity_order.get(row["severity"], 9),
            -row["search_budget_lost_impression_share"],
            -row["search_rank_lost_impression_share"],
            row["campaign_name"],
        )
    )
    return currency_code, campaigns


def build_channel_summary(campaigns: list[dict]) -> list[dict]:
    counter = Counter(row["channel_type"] for row in campaigns)
    return [{"channel_type": key, "count": value} for key, value in counter.most_common()]


def build_problem_items(campaigns: list[dict]) -> list[dict]:
    items = []
    for campaign in campaigns:
        if campaign["flags"] == ["ok"]:
            continue
        recommendation = "sprawdz osobno budzet, ranking, strategie stawek i jakosc ruchu przed decyzja o zmianach"
        items.append(
            {
                "severity": campaign["severity"],
                "campaign_name": campaign["campaign_name"],
                "channel_type": campaign["channel_type"],
                "impression_share": percent_label(campaign["search_impression_share"]),
                "lost_budget": percent_label(campaign["search_budget_lost_impression_share"]),
                "lost_rank": percent_label(campaign["search_rank_lost_impression_share"]),
                "top_share": percent_label(campaign["search_top_impression_share"]),
                "flags": campaign["flags"],
                "recommendation": recommendation,
            }
        )
    return items


def build_impression_share_plan(client_config: ClientConfig) -> ImpressionSharePlan:
    warnings = []
    try:
        _currency_code, campaigns = fetch_impression_share_campaigns(client_config)
    except Exception as exc:
        campaigns = []
        warnings.append(f"Nie udalo sie pobrac udzialu w wyswietleniach z Google Ads API: {exc}")

    if not campaigns:
        warnings.append("Nie znaleziono kampanii z danymi udzialu w wyswietleniach albo nie udalo sie ich pobrac.")

    warnings.append(
        "To zadanie tylko wskazuje utrate udzialu w wyswietleniach. Decyzje o budzetach i stawkach pozostaja w osobnych zadaniach."
    )

    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 aukcji i udzialu w wyswietleniach bedziemy dopisywac osobno po akceptacji uzytkownika."
        )

    return ImpressionSharePlan(
        campaigns=campaigns,
        channel_summary=build_channel_summary(campaigns),
        problem_items=build_problem_items(campaigns),
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_impression_share_plan(domain: str, plan: ImpressionSharePlan) -> 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 udzialu w wyswietleniach",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Kampanie: {len(plan.campaigns)}",
        f"- Elementy do oceny: {len(plan.problem_items)}",
        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.channel_summary:
        lines.extend(["## Podsumowanie po typach kampanii", "", "| Typ | Liczba |", "| --- | --- |"])
        for row in plan.channel_summary:
            lines.append(f"| {row['channel_type']} | {row['count']} |")
        lines.append("")
    if plan.problem_items:
        lines.extend(
            [
                "## Elementy do oceny",
                "",
                "| Waznosc | Kampania | Typ | Udzial | Utrata budzet | Utrata ranking | Top | Flagi | Rekomendacja |",
                "| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for item in plan.problem_items:
            lines.append(
                f"| {item['severity']} | {md_cell(item['campaign_name'])} | {item['channel_type']} | "
                f"{item['impression_share']} | {item['lost_budget']} | {item['lost_rank']} | {item['top_share']} | "
                f"{md_cell(', '.join(item['flags']))} | {md_cell(item['recommendation'])} |"
            )
        lines.append("")
    if plan.campaigns:
        lines.extend(
            [
                "## Kampanie",
                "",
                "| Kampania | Typ | Wyswietlenia | Koszt | Udzial | Utrata budzet | Utrata ranking | Top | Abs. top | Flagi |",
                "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for campaign in plan.campaigns:
            lines.append(
                f"| {md_cell(campaign['campaign_name'])} | {campaign['channel_type']} | {campaign['impressions']} | "
                f"{campaign['cost']} | {percent_label(campaign['search_impression_share'])} | "
                f"{percent_label(campaign['search_budget_lost_impression_share'])} | "
                f"{percent_label(campaign['search_rank_lost_impression_share'])} | "
                f"{percent_label(campaign['search_top_impression_share'])} | "
                f"{percent_label(campaign['search_absolute_top_impression_share'])} | "
                f"{md_cell(', '.join(campaign['flags']))} |"
            )
        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_impression_share_plan(plan: ImpressionSharePlan) -> None:
    print("\nPlan sprawdzenia udzialu w wyswietleniach")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Kampanie", str(len(plan.campaigns))],
            ["Elementy do oceny", str(len(plan.problem_items))],
            ["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.channel_summary:
        print("\nPodsumowanie po typach kampanii")
        print_table(["Typ", "Liczba"], [[row["channel_type"], str(row["count"])] for row in plan.channel_summary])
    if plan.problem_items:
        print("\nElementy do oceny")
        print_table(
            ["Nr", "Waznosc", "Kampania", "Typ", "Udzial", "Utrata budzet", "Utrata ranking", "Flagi"],
            [
                [
                    str(index),
                    item["severity"],
                    item["campaign_name"],
                    item["channel_type"],
                    item["impression_share"],
                    item["lost_budget"],
                    item["lost_rank"],
                    ", ".join(item["flags"]),
                ]
                for index, item in enumerate(plan.problem_items[:30], 1)
            ],
        )
        if len(plan.problem_items) > 30:
            print(f"... oraz {len(plan.problem_items) - 30} kolejnych elementow w pliku planu")
    if plan.campaigns:
        print("\nKampanie")
        print_table(
            ["Nr", "Kampania", "Typ", "Wysw.", "Udzial", "Budzet lost", "Rank lost", "Top", "Flagi"],
            [
                [
                    str(index),
                    campaign["campaign_name"],
                    campaign["channel_type"],
                    str(campaign["impressions"]),
                    percent_label(campaign["search_impression_share"]),
                    percent_label(campaign["search_budget_lost_impression_share"]),
                    percent_label(campaign["search_rank_lost_impression_share"]),
                    percent_label(campaign["search_top_impression_share"]),
                    ", ".join(campaign["flags"]),
                ]
                for index, campaign in enumerate(plan.campaigns[:30], 1)
            ],
        )
    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_impression_share_plan(
    client_config: ClientConfig,
    plan: ImpressionSharePlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem aukcji 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(item["campaign_name"] for item in plan.problem_items[:10]),
            "summary": {
                "campaigns": len(plan.campaigns),
                "problem_items": len(plan.problem_items),
                "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_impression_share(
    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 = ImpressionSharePlan.from_dict(plan_data)
        print_impression_share_plan(plan)
        apply_impression_share_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia udzialu w wyswietleniach...")
    plan = build_impression_share_plan(client_config)
    print_impression_share_plan(plan)
    json_path, md_path = save_impression_share_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(item["campaign_name"] for item in plan.problem_items[:10]),
            "summary": {
                "campaigns": len(plan.campaigns),
                "problem_items": len(plan.problem_items),
                "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 udzialu w wyswietleniach.")
    if show_navigation:
        print_next_navigation(client_config.domain)
