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_remarketing_setup"
TASK_NAME = "Sprawdzenie remarketingu"


SCOPE = [
    {
        "area": "Listy odbiorcow",
        "check": "Pokaz listy odbiorcow z Google Ads, ich typ, status czlonkostwa i rozmiary dla Search oraz Display.",
    },
    {
        "area": "Dynamiczny remarketing",
        "check": "Wypisz kontrole tagowania produktowego i identyfikatorow produktow do recznej oceny.",
    },
    {
        "area": "Powiazanie z PMax",
        "check": "Oznacz ryzyko nakladania remarketingu z PMax jako punkt do recznej oceny.",
    },
    {
        "area": "Gotowosc list",
        "check": "Oznacz listy zbyt male albo zamkniete jako potencjalny problem wykorzystania w kampaniach.",
    },
]


DYNAMIC_REMARKETING_CHECKS = [
    "czy tag Google Ads / GTM przekazuje identyfikatory produktow zgodne z feedem",
    "czy zdarzenia e-commerce rozrozniaja view_item, add_to_cart i purchase",
    "czy remarketing dynamiczny ma dostep do feedu produktowego",
    "czy listy odbiorcow sa wystarczajaco duze dla Search i Display",
    "czy PMax nie przechwytuje calego remarketingu bez osobnej kontroli",
]


OUT_OF_SCOPE = [
    "budzety i pacing budzetu",
    "strategie stawek oraz cele Docelowy ROAS/Docelowy CPA",
    "tworzenie reklam i kreacji remarketingowych",
    "problemy feedu i Merchant Center poza kontrola identyfikatorow produktow",
    "wdrazanie zmian w tagowaniu albo listach odbiorcow",
]


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


def size_label(search_size: int, display_size: int) -> str:
    max_size = max(search_size, display_size)
    if max_size <= 0:
        return "brak rozmiaru"
    if max_size < 100:
        return "bardzo mala lista"
    if max_size < 1000:
        return "mala lista"
    return "rozmiar ok"


def user_list_flags(row: dict) -> list[str]:
    flags = []
    if row["membership_status"] and row["membership_status"] != "OPEN":
        flags.append("lista zamknieta")
    if row["size_status"] != "rozmiar ok":
        flags.append(row["size_status"])
    if row["type"] in {"UNKNOWN", "UNSPECIFIED"}:
        flags.append("nieznany typ")
    return flags or ["ok"]


def fetch_user_lists(client_config: ClientConfig) -> list[dict]:
    google_client = get_google_ads_client(use_proto_plus=True)
    rows = run_query(
        google_client,
        client_config.safe_customer_id,
        """
        SELECT
          user_list.id,
          user_list.name,
          user_list.type,
          user_list.membership_status,
          user_list.size_for_search,
          user_list.size_for_display
        FROM user_list
        """,
    )

    user_lists = []
    for row in rows:
        user_list = row.user_list
        search_size = safe_int(user_list.size_for_search)
        display_size = safe_int(user_list.size_for_display)
        record = {
            "user_list_id": str(user_list.id),
            "name": user_list.name,
            "type": enum_name(user_list.type),
            "membership_status": enum_name(user_list.membership_status),
            "size_for_search": search_size,
            "size_for_display": display_size,
            "size_status": size_label(search_size, display_size),
        }
        record["flags"] = user_list_flags(record)
        user_lists.append(record)
    user_lists.sort(key=lambda row: (row["size_status"], row["name"]))
    return user_lists


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


def build_remarketing_setup_plan(client_config: ClientConfig) -> RemarketingSetupPlan:
    warnings = []
    try:
        user_lists = fetch_user_lists(client_config)
    except Exception as exc:
        user_lists = []
        warnings.append(f"Nie udalo sie pobrac list odbiorcow z Google Ads API: {exc}")

    if not user_lists:
        warnings.append("Nie znaleziono list odbiorcow albo nie udalo sie ich pobrac.")

    warnings.append(
        "Dynamiczny remarketing wymaga potwierdzenia tagowania produktowego w zadaniu Pomiar i konwersje oraz zgodnosci feedu w zadaniu Feed i Merchant Center."
    )
    warnings.append(
        "Konflikt remarketingu z PMax wymaga recznej oceny razem z zadaniem Sprawdzenie struktury PMax."
    )

    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 remarketingu bedziemy dopisywac osobno po akceptacji uzytkownika."
        )

    return RemarketingSetupPlan(
        user_lists=user_lists,
        list_type_summary=build_list_type_summary(user_lists),
        dynamic_remarketing_checks=DYNAMIC_REMARKETING_CHECKS,
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_remarketing_setup_plan(domain: str, plan: RemarketingSetupPlan) -> 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 remarketingu",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Listy odbiorcow: {len(plan.user_lists)}",
        f"- Typy list: {len(plan.list_type_summary)}",
        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.list_type_summary:
        lines.extend(["## Podsumowanie typow list", "", "| Typ | Liczba |", "| --- | --- |"])
        for row in plan.list_type_summary:
            lines.append(f"| {row['type']} | {row['count']} |")
        lines.append("")
    if plan.user_lists:
        lines.extend(
            [
                "## Listy odbiorcow",
                "",
                "| Lista | Typ | Status | Search size | Display size | Flagi |",
                "| --- | --- | --- | --- | --- | --- |",
            ]
        )
        for row in plan.user_lists:
            lines.append(
                f"| {md_cell(row['name'])} | {row['type']} | {row['membership_status']} | "
                f"{row['size_for_search']} | {row['size_for_display']} | {md_cell(', '.join(row['flags']))} |"
            )
        lines.append("")
    lines.extend(["## Kontrole dynamicznego remarketingu", ""])
    lines.extend(f"- {item}" for item in plan.dynamic_remarketing_checks)
    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_remarketing_setup_plan(plan: RemarketingSetupPlan) -> None:
    print("\nPlan sprawdzenia remarketingu")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Listy odbiorcow", str(len(plan.user_lists))],
            ["Typy list", str(len(plan.list_type_summary))],
            ["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.list_type_summary:
        print("\nPodsumowanie typow list")
        print_table(
            ["Typ", "Liczba"],
            [[row["type"], str(row["count"])] for row in plan.list_type_summary],
        )
    if plan.user_lists:
        print("\nListy odbiorcow")
        print_table(
            ["Nr", "Lista", "Typ", "Status", "Search", "Display", "Flagi"],
            [
                [
                    str(index),
                    row["name"],
                    row["type"],
                    row["membership_status"],
                    str(row["size_for_search"]),
                    str(row["size_for_display"]),
                    ", ".join(row["flags"]),
                ]
                for index, row in enumerate(plan.user_lists[:30], 1)
            ],
        )
        if len(plan.user_lists) > 30:
            print(f"... oraz {len(plan.user_lists) - 30} kolejnych list w pliku planu")
    print("\nKontrole dynamicznego remarketingu")
    print_table(
        ["Nr", "Kontrola"],
        [[str(index), item] for index, item in enumerate(plan.dynamic_remarketing_checks, 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_remarketing_setup_plan(
    client_config: ClientConfig,
    plan: RemarketingSetupPlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem remarketingu 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": "",
            "summary": {
                "user_lists": len(plan.user_lists),
                "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_remarketing_setup(
    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 = RemarketingSetupPlan.from_dict(plan_data)
        print_remarketing_setup_plan(plan)
        apply_remarketing_setup_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia remarketingu...")
    plan = build_remarketing_setup_plan(client_config)
    print_remarketing_setup_plan(plan)
    json_path, md_path = save_remarketing_setup_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": "",
            "summary": {
                "user_lists": len(plan.user_lists),
                "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 remarketingu.")
    if show_navigation:
        print_next_navigation(client_config.domain)
