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_keyword_statuses"
TASK_NAME = "Sprawdzenie statusow slow kluczowych"


SCOPE = [
    {
        "area": "Status slow kluczowych",
        "check": "Pokaz status kampanii, grupy reklam i slowa kluczowego dla aktywnych kampanii Search.",
    },
    {
        "area": "Polityki",
        "check": "Oznacz slowa z problemami polityk, jezeli Google Ads API udostepnia status zatwierdzenia.",
    },
    {
        "area": "Jakosc techniczna",
        "check": "Pokaz quality score i oznacz bardzo niskie wyniki jako techniczny sygnal do sprawdzenia.",
    },
    {
        "area": "Oddzielenie od zapytan",
        "check": "Nie analizuj tutaj search terms, wykluczen ani decyzji o dodawaniu nowych fraz.",
    },
]


OUT_OF_SCOPE = [
    "analiza zapytan uzytkownikow",
    "dodawanie, usuwanie albo wykluczanie slow kluczowych",
    "budzety i wykorzystanie budzetu",
    "strategie stawek oraz cele Docelowy ROAS/Docelowy CPA",
    "wdrazanie zmian slow kluczowych na koncie Google Ads",
]


PROBLEM_APPROVAL_STATUSES = {
    "DISAPPROVED",
    "APPROVED_LIMITED",
    "AREA_OF_INTEREST_ONLY",
    "UNDER_REVIEW",
    "UNKNOWN",
    "UNSPECIFIED",
}


PROBLEM_STATUS_FIELDS = {
    "PAUSED",
    "REMOVED",
    "UNKNOWN",
    "UNSPECIFIED",
}


@dataclass
class KeywordStatusPlan:
    keywords: list[dict]
    status_summary: list[dict]
    approval_summary: list[dict]
    quality_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,
            "keywords": self.keywords,
            "status_summary": self.status_summary,
            "approval_summary": self.approval_summary,
            "quality_summary": self.quality_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) -> "KeywordStatusPlan":
        return cls(
            keywords=data.get("keywords", []),
            status_summary=data.get("status_summary", []),
            approval_summary=data.get("approval_summary", []),
            quality_summary=data.get("quality_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 safe_quality_score(value: Any) -> int:
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def quality_bucket(score: int) -> str:
    if score <= 0:
        return "brak danych"
    if score <= 3:
        return "niski"
    if score <= 6:
        return "sredni"
    return "dobry"


def keyword_severity(row: dict) -> str:
    if row["approval_status"] == "DISAPPROVED":
        return "wysokie"
    if row["keyword_status"] in PROBLEM_STATUS_FIELDS or row["ad_group_status"] in PROBLEM_STATUS_FIELDS:
        return "srednie"
    if row["approval_status"] in {"APPROVED_LIMITED", "AREA_OF_INTEREST_ONLY"}:
        return "srednie"
    if row["quality_score"] and row["quality_score"] <= 3:
        return "srednie"
    if row["approval_status"] in {"UNDER_REVIEW", "UNKNOWN", "UNSPECIFIED"}:
        return "niskie"
    return "ok"


def keyword_flags(row: dict) -> list[str]:
    flags = []
    if row["campaign_status"] in PROBLEM_STATUS_FIELDS:
        flags.append(f"kampania: {row['campaign_status']}")
    if row["ad_group_status"] in PROBLEM_STATUS_FIELDS:
        flags.append(f"grupa reklam: {row['ad_group_status']}")
    if row["keyword_status"] in PROBLEM_STATUS_FIELDS:
        flags.append(f"slowo: {row['keyword_status']}")
    if row["approval_status"] in PROBLEM_APPROVAL_STATUSES:
        flags.append(f"polityka: {row['approval_status']}")
    if row["quality_score"] and row["quality_score"] <= 3:
        flags.append(f"niski quality score: {row['quality_score']}")
    return flags or ["ok"]


def fetch_keywords(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
          campaign.id,
          campaign.name,
          campaign.status,
          campaign.advertising_channel_type,
          ad_group.id,
          ad_group.name,
          ad_group.status,
          ad_group_criterion.criterion_id,
          ad_group_criterion.status,
          ad_group_criterion.keyword.text,
          ad_group_criterion.keyword.match_type,
          ad_group_criterion.quality_info.quality_score
        FROM keyword_view
        WHERE campaign.status != 'REMOVED'
          AND ad_group.status != 'REMOVED'
          AND ad_group_criterion.status != 'REMOVED'
          AND ad_group_criterion.type = 'KEYWORD'
        """,
    )

    keywords = []
    for row in rows:
        criterion = row.ad_group_criterion
        keyword = criterion.keyword
        quality_score = safe_quality_score(criterion.quality_info.quality_score)
        record = {
            "campaign_id": str(row.campaign.id),
            "campaign_name": row.campaign.name,
            "campaign_status": enum_name(row.campaign.status),
            "channel_type": enum_name(row.campaign.advertising_channel_type),
            "ad_group_id": str(row.ad_group.id),
            "ad_group_name": row.ad_group.name,
            "ad_group_status": enum_name(row.ad_group.status),
            "criterion_id": str(criterion.criterion_id),
            "keyword_text": keyword.text,
            "match_type": enum_name(keyword.match_type),
            "keyword_status": enum_name(criterion.status),
            "approval_status": "niedostepne w API",
            "quality_score": quality_score,
            "quality_bucket": quality_bucket(quality_score),
        }
        record["severity"] = keyword_severity(record)
        record["flags"] = keyword_flags(record)
        keywords.append(record)

    severity_order = {"wysokie": 0, "srednie": 1, "niskie": 2, "ok": 9}
    keywords.sort(
        key=lambda row: (
            severity_order.get(row["severity"], 9),
            row["campaign_name"],
            row["ad_group_name"],
            row["keyword_text"],
        )
    )
    return keywords


def build_counter_summary(rows: list[dict], field: str, label: str) -> list[dict]:
    counter = Counter(row.get(field, "") or "(brak)" for row in rows)
    return [{label: key, "count": value} for key, value in counter.most_common()]


def build_problem_items(keywords: list[dict]) -> list[dict]:
    problem_items = []
    for keyword in keywords:
        if keyword["flags"] == ["ok"]:
            continue
        problem_items.append(
            {
                "severity": keyword["severity"],
                "campaign_name": keyword["campaign_name"],
                "ad_group_name": keyword["ad_group_name"],
                "keyword_text": keyword["keyword_text"],
                "match_type": keyword["match_type"],
                "keyword_status": keyword["keyword_status"],
                "approval_status": keyword["approval_status"],
                "quality_score": keyword["quality_score"],
                "flags": keyword["flags"],
                "recommendation": "sprawdz status i przyczyne ograniczenia slowa kluczowego w Google Ads",
            }
        )
    severity_order = {"wysokie": 0, "srednie": 1, "niskie": 2, "ok": 9}
    problem_items.sort(
        key=lambda row: (
            severity_order.get(row["severity"], 9),
            row["campaign_name"],
            row["ad_group_name"],
            row["keyword_text"],
        )
    )
    return problem_items


def build_keyword_status_plan(client_config: ClientConfig) -> KeywordStatusPlan:
    warnings = []
    try:
        keywords = fetch_keywords(client_config)
    except Exception as exc:
        keywords = []
        warnings.append(f"Nie udalo sie pobrac slow kluczowych z Google Ads API: {exc}")

    if not keywords:
        warnings.append("Nie znaleziono slow kluczowych albo nie udalo sie ich pobrac.")

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

    return KeywordStatusPlan(
        keywords=keywords,
        status_summary=build_counter_summary(keywords, "keyword_status", "status"),
        approval_summary=build_counter_summary(keywords, "approval_status", "approval_status"),
        quality_summary=build_counter_summary(keywords, "quality_bucket", "quality_bucket"),
        problem_items=build_problem_items(keywords),
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_keyword_status_plan(domain: str, plan: KeywordStatusPlan) -> 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 statusow slow kluczowych",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Slowa kluczowe: {len(plan.keywords)}",
        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.problem_items:
        lines.extend(
            [
                "## Elementy do oceny",
                "",
                "| Waznosc | Kampania | Grupa reklam | Slowo | Dopasowanie | Status | Polityka | QS | Flagi | Rekomendacja |",
                "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for item in plan.problem_items:
            lines.append(
                f"| {item['severity']} | {md_cell(item['campaign_name'])} | {md_cell(item['ad_group_name'])} | "
                f"{md_cell(item['keyword_text'])} | {item['match_type']} | {item['keyword_status']} | "
                f"{item['approval_status']} | {item['quality_score']} | {md_cell(', '.join(item['flags']))} | "
                f"{md_cell(item['recommendation'])} |"
            )
        lines.append("")
    if plan.status_summary:
        lines.extend(["## Statusy slow kluczowych", "", "| Status | Liczba |", "| --- | --- |"])
        for row in plan.status_summary:
            lines.append(f"| {row['status']} | {row['count']} |")
        lines.append("")
    if plan.approval_summary:
        lines.extend(["## Statusy zatwierdzenia", "", "| Status polityki | Liczba |", "| --- | --- |"])
        for row in plan.approval_summary:
            lines.append(f"| {row['approval_status']} | {row['count']} |")
        lines.append("")
    if plan.quality_summary:
        lines.extend(["## Quality score", "", "| Koszyk | Liczba |", "| --- | --- |"])
        for row in plan.quality_summary:
            lines.append(f"| {row['quality_bucket']} | {row['count']} |")
        lines.append("")
    if plan.keywords:
        lines.extend(
            [
                "## Slowa kluczowe",
                "",
                "| Kampania | Grupa reklam | Slowo | Dopasowanie | Status | Polityka | QS | Flagi |",
                "| --- | --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for keyword in plan.keywords:
            lines.append(
                f"| {md_cell(keyword['campaign_name'])} | {md_cell(keyword['ad_group_name'])} | "
                f"{md_cell(keyword['keyword_text'])} | {keyword['match_type']} | {keyword['keyword_status']} | "
                f"{keyword['approval_status']} | {keyword['quality_score']} | {md_cell(', '.join(keyword['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_keyword_status_plan(plan: KeywordStatusPlan) -> None:
    print("\nPlan sprawdzenia statusow slow kluczowych")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Slowa kluczowe", str(len(plan.keywords))],
            ["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.problem_items:
        print("\nElementy do oceny")
        print_table(
            ["Nr", "Waznosc", "Kampania", "Grupa reklam", "Slowo", "Status", "Polityka", "QS", "Flagi"],
            [
                [
                    str(index),
                    item["severity"],
                    item["campaign_name"],
                    item["ad_group_name"],
                    item["keyword_text"],
                    item["keyword_status"],
                    item["approval_status"],
                    str(item["quality_score"]),
                    ", ".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.status_summary:
        print("\nStatusy slow kluczowych")
        print_table(["Status", "Liczba"], [[row["status"], str(row["count"])] for row in plan.status_summary])
    if plan.approval_summary:
        print("\nStatusy zatwierdzenia")
        print_table(
            ["Status polityki", "Liczba"],
            [[row["approval_status"], str(row["count"])] for row in plan.approval_summary],
        )
    if plan.quality_summary:
        print("\nQuality score")
        print_table(["Koszyk", "Liczba"], [[row["quality_bucket"], str(row["count"])] for row in plan.quality_summary])
    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_keyword_status_plan(
    client_config: ClientConfig,
    plan: KeywordStatusPlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem statusow slow kluczowych 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": {
                "keywords": len(plan.keywords),
                "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_keyword_statuses(
    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 = KeywordStatusPlan.from_dict(plan_data)
        print_keyword_status_plan(plan)
        apply_keyword_status_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia statusow slow kluczowych...")
    plan = build_keyword_status_plan(client_config)
    print_keyword_status_plan(plan)
    json_path, md_path = save_keyword_status_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": {
                "keywords": len(plan.keywords),
                "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 statusow slow kluczowych.")
    if show_navigation:
        print_next_navigation(client_config.domain)
