from __future__ import annotations

import json
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_search_terms"
TASK_NAME = "Analiza zapytan i wykluczen"
MAX_SEARCH_TERMS = 100


SCOPE = [
    {
        "area": "Zapytania 7 dni",
        "check": "Pokaz zapytania uzytkownikow z ostatnich 7 dni posortowane po koszcie.",
    },
    {
        "area": "Kandydaci do wykluczen",
        "check": "Oznacz zapytania z kliknieciami i kosztem bez konwersji jako material do recznej oceny.",
    },
    {
        "area": "Broad match i jakosc dopasowan",
        "check": "Zbierz kontekst kampanii i grup reklam, aby latwiej ocenic, czy ruch pasuje do intencji.",
    },
    {
        "area": "Brand / non-brand",
        "check": "Nie rozstrzygaj automatycznie brandu; pokaz zapytania tak, aby agent mogl ocenic intencje.",
    },
]


OUT_OF_SCOPE = [
    "budzety i pacing budzetu",
    "strategie stawek oraz cele Docelowy ROAS/Docelowy CPA",
    "podstawowe ustawienia kampanii, np. lokalizacje i sieci",
    "automatyczne dodawanie wykluczen do konta",
    "ocena reklam RSA i zasobow reklam",
]


@dataclass
class SearchTermsPlan:
    currency_code: str
    search_terms: 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,
            "search_terms": self.search_terms,
            "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) -> "SearchTermsPlan":
        return cls(
            currency_code=data.get("currency_code", ""),
            search_terms=data.get("search_terms", []),
            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 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 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 action_label(clicks: int, cost_micros: int, conversions: float) -> str:
    if clicks <= 0:
        return "brak klikniec"
    if conversions > 0:
        return "zostaw do oceny pozytywnej"
    if clicks >= 10:
        return "pilny kandydat do oceny"
    if clicks >= 5:
        return "kandydat do oceny"
    if cost_micros > 0:
        return "obserwuj"
    return "brak kosztu"


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_search_terms(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,
        f"""
        SELECT
          campaign.id,
          campaign.name,
          campaign.advertising_channel_type,
          ad_group.id,
          ad_group.name,
          search_term_view.search_term,
          metrics.impressions,
          metrics.clicks,
          metrics.cost_micros,
          metrics.conversions,
          metrics.conversions_value
        FROM search_term_view
        WHERE campaign.status = 'ENABLED'
          AND ad_group.status = 'ENABLED'
          AND campaign.advertising_channel_type = 'SEARCH'
          AND segments.date DURING LAST_7_DAYS
        ORDER BY metrics.cost_micros DESC
        LIMIT {MAX_SEARCH_TERMS}
        """,
    )

    search_terms = []
    for row in rows:
        clicks = safe_int(row.metrics.clicks)
        cost_micros = safe_int(row.metrics.cost_micros)
        conversions = safe_float(row.metrics.conversions)
        search_terms.append(
            {
                "campaign_id": str(row.campaign.id),
                "campaign_name": row.campaign.name,
                "channel_type": enum_name(row.campaign.advertising_channel_type),
                "ad_group_id": str(row.ad_group.id),
                "ad_group_name": row.ad_group.name,
                "search_term": str(row.search_term_view.search_term or ""),
                "impressions": safe_int(row.metrics.impressions),
                "clicks": clicks,
                "cost_micros": cost_micros,
                "conversions": conversions,
                "conversion_value": safe_float(row.metrics.conversions_value),
                "action_label": action_label(clicks, cost_micros, conversions),
            }
        )
    return currency_code, search_terms


def build_search_terms_plan(client_config: ClientConfig) -> SearchTermsPlan:
    warnings = []
    try:
        currency_code, search_terms = fetch_search_terms(client_config)
    except Exception as exc:
        currency_code = ""
        search_terms = []
        warnings.append(f"Nie udalo sie pobrac zapytan z Google Ads API: {exc}")

    if not search_terms:
        warnings.append("Nie znaleziono zapytan Search z ostatnich 7 dni albo nie udalo sie ich pobrac.")

    rules = rules_for_task(TASK_ID)
    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
    ]
    if not knowledge_rules:
        warnings.append(
            "Do tego zadania nie przypisano jeszcze regul z bazy wiedzy. "
            "Reguly dotyczace zapytan i wykluczen bedziemy dopisywac osobno po akceptacji uzytkownika."
        )

    return SearchTermsPlan(
        currency_code=currency_code,
        search_terms=search_terms,
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_search_terms_plan(domain: str, plan: SearchTermsPlan) -> 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: Analiza zapytan i wykluczen",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Zapytania z ostatnich 7 dni: {len(plan.search_terms)}",
        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"| {row.get('area', '')} | {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.search_terms:
        lines.extend(
            [
                "## Zapytania z ostatnich 7 dni",
                "",
                "| Zapytanie | Kampania | Grupa reklam | Klikniecia | Koszt | Konwersje | Ocena |",
                "| --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for term in plan.search_terms:
            lines.append(
                f"| {term['search_term']} | {term['campaign_name']} | {term['ad_group_name']} | "
                f"{term['clicks']} | {format_money(term['cost_micros'], plan.currency_code)} | "
                f"{format_decimal(term['conversions'])} | {term['action_label']} |"
            )
        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"| {rule.get('id', '')} | {rule.get('topic', '')} | "
                f"{rule.get('recommendation', '')} | {rule.get('risk', '')} |"
            )
        lines.append("")
    md_path.write_text("\n".join(lines), encoding="utf-8")
    return json_path, md_path


def print_search_terms_plan(plan: SearchTermsPlan) -> None:
    print("\nPlan analizy zapytan i wykluczen")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Zapytania z 7 dni", str(len(plan.search_terms))],
            ["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.search_terms:
        print("\nZapytania z ostatnich 7 dni")
        print_table(
            ["Nr", "Zapytanie", "Kampania", "Klik.", "Koszt", "Konw.", "Ocena"],
            [
                [
                    str(index),
                    term["search_term"],
                    term["campaign_name"],
                    str(term["clicks"]),
                    format_money(term["cost_micros"], plan.currency_code),
                    format_decimal(term["conversions"]),
                    term["action_label"],
                ]
                for index, term in enumerate(plan.search_terms[:30], 1)
            ],
        )
        if len(plan.search_terms) > 30:
            print(f"... oraz {len(plan.search_terms) - 30} kolejnych zapytan 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_search_terms_plan(
    client_config: ClientConfig,
    plan: SearchTermsPlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem zapytan i nie dodaje wykluczen 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(sorted({term["campaign_name"] for term in plan.search_terms})[:10]),
            "summary": {
                "search_terms": len(plan.search_terms),
                "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_search_terms(
    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 = SearchTermsPlan.from_dict(plan_data)
        print_search_terms_plan(plan)
        apply_search_terms_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan analizy zapytan i wykluczen...")
    plan = build_search_terms_plan(client_config)
    print_search_terms_plan(plan)
    json_path, md_path = save_search_terms_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(sorted({term["campaign_name"] for term in plan.search_terms})[:10]),
            "summary": {
                "search_terms": len(plan.search_terms),
                "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 zapytan.")
    if show_navigation:
        print_next_navigation(client_config.domain)
