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_rsa_assets"
TASK_NAME = "Sprawdzenie reklam RSA i zasobow"
MAX_RSA_ADS = 100


SCOPE = [
    {
        "area": "Reklamy RSA",
        "check": "Pokaz aktywne reklamy RSA w aktywnych kampaniach Search i grupach reklam.",
    },
    {
        "area": "Naglowki",
        "check": "Policz naglowki i oznacz reklamy z mala liczba wariantow albo duplikatami.",
    },
    {
        "area": "Teksty reklam",
        "check": "Policz opisy i oznacz reklamy z mala liczba wariantow.",
    },
    {
        "area": "DKI",
        "check": "Oznacz uzycie Dynamic Keyword Insertion jako element wymagajacy recznej oceny.",
    },
    {
        "area": "Final URL",
        "check": "Sprawdz, czy reklama ma finalny adres URL.",
    },
]


OUT_OF_SCOPE = [
    "zapytania uzytkownikow i wykluczenia",
    "budzety i pacing budzetu",
    "strategie stawek oraz cele Docelowy ROAS/Docelowy CPA",
    "podstawowe ustawienia kampanii, np. lokalizacje i sieci",
    "automatyczne tworzenie albo edycja reklam",
]


@dataclass
class RsaAssetsPlan:
    ads: 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,
            "ads": self.ads,
            "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) -> "RsaAssetsPlan":
        return cls(
            ads=data.get("ads", []),
            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 text_asset_values(assets: Any) -> list[str]:
    values = []
    for asset in assets or []:
        text = str(getattr(asset, "text", "") or "").strip()
        if text:
            values.append(text)
    return values


def has_dki(values: list[str]) -> bool:
    return any("{keyword:" in value.casefold() for value in values)


def duplicate_count(values: list[str]) -> int:
    normalized = [value.casefold().strip() for value in values if value.strip()]
    return len(normalized) - len(set(normalized))


def risk_labels(headlines: list[str], descriptions: list[str], final_urls: list[str]) -> list[str]:
    risks = []
    if len(headlines) < 8:
        risks.append("malo naglowkow")
    if len(descriptions) < 3:
        risks.append("malo opisow")
    if duplicate_count(headlines) > 0:
        risks.append("duplikaty naglowkow")
    if has_dki(headlines + descriptions):
        risks.append("sprawdz DKI")
    if not final_urls:
        risks.append("brak final URL")
    return risks or ["do oceny"]


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


def fetch_rsa_ads(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,
        f"""
        SELECT
          campaign.id,
          campaign.name,
          ad_group.id,
          ad_group.name,
          ad_group_ad.ad.id,
          ad_group_ad.status,
          ad_group_ad.ad.final_urls,
          ad_group_ad.ad.responsive_search_ad.headlines,
          ad_group_ad.ad.responsive_search_ad.descriptions
        FROM ad_group_ad
        WHERE campaign.status = 'ENABLED'
          AND ad_group.status = 'ENABLED'
          AND ad_group_ad.status != 'REMOVED'
          AND ad_group_ad.ad.type = 'RESPONSIVE_SEARCH_AD'
        LIMIT {MAX_RSA_ADS}
        """,
    )

    ads = []
    for row in rows:
        ad = row.ad_group_ad.ad
        rsa = ad.responsive_search_ad
        headlines = text_asset_values(rsa.headlines)
        descriptions = text_asset_values(rsa.descriptions)
        final_urls = [str(url) for url in ad.final_urls]
        risks = risk_labels(headlines, descriptions, final_urls)
        ads.append(
            {
                "campaign_id": str(row.campaign.id),
                "campaign_name": row.campaign.name,
                "ad_group_id": str(row.ad_group.id),
                "ad_group_name": row.ad_group.name,
                "ad_id": str(ad.id),
                "status": enum_name(row.ad_group_ad.status),
                "headline_count": len(headlines),
                "description_count": len(descriptions),
                "headlines": headlines,
                "descriptions": descriptions,
                "final_urls": final_urls,
                "has_dki": has_dki(headlines + descriptions),
                "duplicate_headlines": duplicate_count(headlines),
                "risk_labels": risks,
            }
        )
    return ads


def build_rsa_assets_plan(client_config: ClientConfig) -> RsaAssetsPlan:
    warnings = []
    try:
        ads = fetch_rsa_ads(client_config)
    except Exception as exc:
        ads = []
        warnings.append(f"Nie udalo sie pobrac reklam RSA z Google Ads API: {exc}")

    if not ads:
        warnings.append("Nie znaleziono aktywnych reklam RSA 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 RSA i zasobow bedziemy dopisywac osobno po akceptacji uzytkownika."
        )

    ads.sort(key=lambda row: (len(row["risk_labels"]), row["campaign_name"], row["ad_group_name"]), reverse=True)
    return RsaAssetsPlan(
        ads=ads,
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_rsa_assets_plan(domain: str, plan: RsaAssetsPlan) -> 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 reklam RSA i zasobow",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Reklamy RSA: {len(plan.ads)}",
        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.ads:
        lines.extend(
            [
                "## Reklamy RSA",
                "",
                "| Kampania | Grupa reklam | Reklama | Naglowki | Opisy | Ryzyka |",
                "| --- | --- | --- | --- | --- | --- |",
            ]
        )
        for ad in plan.ads:
            lines.append(
                f"| {md_cell(ad['campaign_name'])} | {md_cell(ad['ad_group_name'])} | "
                f"{md_cell(ad['ad_id'])} | {ad['headline_count']} | {ad['description_count']} | "
                f"{md_cell(', '.join(ad['risk_labels']))} |"
            )
        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_rsa_assets_plan(plan: RsaAssetsPlan) -> None:
    print("\nPlan sprawdzenia reklam RSA i zasobow")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Reklamy RSA", str(len(plan.ads))],
            ["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.ads:
        print("\nReklamy RSA")
        print_table(
            ["Nr", "Kampania", "Grupa reklam", "Naglowki", "Opisy", "Ryzyka"],
            [
                [
                    str(index),
                    ad["campaign_name"],
                    ad["ad_group_name"],
                    str(ad["headline_count"]),
                    str(ad["description_count"]),
                    ", ".join(ad["risk_labels"]),
                ]
                for index, ad in enumerate(plan.ads[:30], 1)
            ],
        )
        if len(plan.ads) > 30:
            print(f"... oraz {len(plan.ads) - 30} kolejnych reklam 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_rsa_assets_plan(
    client_config: ClientConfig,
    plan: RsaAssetsPlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem reklam RSA i nie edytuje reklam 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({ad["campaign_name"] for ad in plan.ads})[:10]),
            "summary": {
                "ads": len(plan.ads),
                "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_rsa_assets(
    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 = RsaAssetsPlan.from_dict(plan_data)
        print_rsa_assets_plan(plan)
        apply_rsa_assets_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia reklam RSA i zasobow...")
    plan = build_rsa_assets_plan(client_config)
    print_rsa_assets_plan(plan)
    json_path, md_path = save_rsa_assets_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({ad["campaign_name"] for ad in plan.ads})[:10]),
            "summary": {
                "ads": len(plan.ads),
                "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 reklam RSA.")
    if show_navigation:
        print_next_navigation(client_config.domain)
