from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path

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_basic_settings"
TASK_NAME = "Sprawdzenie podstawowych ustawien Search"


SCOPE = [
    {
        "area": "Lokalizacje",
        "check": "Sprawdz typ kierowania lokalizacji, zwlaszcza Obecnosc vs Obecnosc lub zainteresowanie.",
    },
    {
        "area": "Sieci",
        "check": "Sprawdz, czy kampanie Search nie maja niechcaco wlaczonej sieci reklamowej albo partnerow wyszukiwania.",
    },
    {
        "area": "Jezyki",
        "check": "Sprawdz, czy ustawienia jezykowe sa zgodne z rynkiem klienta.",
    },
    {
        "area": "Harmonogram reklam",
        "check": "Sprawdz, czy harmonogram jest swiadomie ustawiony albo czy kampania dziala caly czas.",
    },
]


OUT_OF_SCOPE = [
    "budzety i wykorzystanie budzetu",
    "strategie stawek i uczenie strategii",
    "zapytania uzytkownikow oraz wykluczenia",
    "reklamy RSA i zasoby reklam",
    "wyniki kampanii oraz rentownosc",
]


@dataclass
class SearchBasicSettingsPlan:
    campaigns: 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,
            "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) -> "SearchBasicSettingsPlan":
        return cls(
            campaigns=data.get("campaigns", []),
            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) -> str:
    name = getattr(value, "name", None)
    if name:
        return name
    return str(value)


def human_geo(value: str) -> str:
    return {
        "PRESENCE": "Obecnosc",
        "PRESENCE_OR_INTEREST": "Obecnosc lub zainteresowanie",
        "SEARCH_INTEREST": "Zainteresowanie wyszukiwaniem",
    }.get(value, value)


def yes_no(value: bool) -> str:
    return "TAK" if value else "NIE"


def fetch_search_campaigns(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,
          campaign.geo_target_type_setting.positive_geo_target_type,
          campaign.network_settings.target_google_search,
          campaign.network_settings.target_search_network,
          campaign.network_settings.target_partner_search_network,
          campaign.network_settings.target_content_network
        FROM campaign
        WHERE campaign.advertising_channel_type = 'SEARCH'
          AND campaign.status != 'REMOVED'
        """,
    )
    campaigns = []
    for row in rows:
        campaign = row.campaign
        positive_geo = enum_name(campaign.geo_target_type_setting.positive_geo_target_type)
        campaigns.append(
            {
                "campaign_id": str(campaign.id),
                "campaign_name": campaign.name,
                "status": enum_name(campaign.status),
                "positive_geo_target_type": positive_geo,
                "positive_geo_target_type_label": human_geo(positive_geo),
                "target_google_search": bool(campaign.network_settings.target_google_search),
                "target_search_network": bool(campaign.network_settings.target_search_network),
                "target_partner_search_network": bool(campaign.network_settings.target_partner_search_network),
                "target_content_network": bool(campaign.network_settings.target_content_network),
            }
        )
    return campaigns


def build_search_basic_settings_plan(client_config: ClientConfig) -> SearchBasicSettingsPlan:
    warnings = []
    try:
        campaigns = fetch_search_campaigns(client_config)
    except Exception as exc:
        campaigns = []
        warnings.append(f"Nie udalo sie pobrac kampanii Search z Google Ads API: {exc}")

    if not campaigns:
        warnings.append("Nie znaleziono kampanii Search 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. "
            "Uzyj `python gads.py wiedza przypisz --restart`, gdy bedziemy wybierac reguly dla Search."
        )

    return SearchBasicSettingsPlan(
        campaigns=campaigns,
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_search_basic_settings_plan(domain: str, plan: SearchBasicSettingsPlan) -> 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 podstawowych ustawien Search",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Kampanie Search: {len(plan.campaigns)}",
        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.campaigns:
        lines.extend(
            [
                "## Kampanie Search",
                "",
                "| Kampania | Status | Lokalizacje | Google Search | Search Network | Partnerzy | Siec reklamowa |",
                "| --- | --- | --- | --- | --- | --- | --- |",
            ]
        )
        for campaign in plan.campaigns:
            lines.append(
                f"| {campaign['campaign_name']} | {campaign['status']} | "
                f"{campaign.get('positive_geo_target_type_label', campaign['positive_geo_target_type'])} | "
                f"{yes_no(campaign['target_google_search'])} | "
                f"{yes_no(campaign['target_search_network'])} | "
                f"{yes_no(campaign['target_partner_search_network'])} | "
                f"{yes_no(campaign['target_content_network'])} |"
            )
        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_basic_settings_plan(plan: SearchBasicSettingsPlan) -> None:
    print("\nPlan sprawdzenia podstawowych ustawien Search")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Kampanie Search", str(len(plan.campaigns))],
            ["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.campaigns:
        print("\nKampanie Search")
        print_table(
            ["Nr", "Kampania", "Status", "Lokalizacje", "Partnerzy", "Siec reklamowa"],
            [
                [
                    str(index),
                    campaign["campaign_name"],
                    campaign["status"],
                    campaign.get("positive_geo_target_type_label", campaign["positive_geo_target_type"]),
                    yes_no(campaign["target_partner_search_network"]),
                    yes_no(campaign["target_content_network"]),
                ]
                for index, campaign in enumerate(plan.campaigns, 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_search_basic_settings_plan(
    client_config: ClientConfig,
    plan: SearchBasicSettingsPlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem ustawien 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(campaign["campaign_name"] for campaign in plan.campaigns[:10]),
            "summary": {
                "campaigns": len(plan.campaigns),
                "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_basic_settings(
    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 = SearchBasicSettingsPlan.from_dict(plan_data)
        print_search_basic_settings_plan(plan)
        apply_search_basic_settings_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia podstawowych ustawien Search...")
    plan = build_search_basic_settings_plan(client_config)
    print_search_basic_settings_plan(plan)
    json_path, md_path = save_search_basic_settings_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(campaign["campaign_name"] for campaign in plan.campaigns[:10]),
            "summary": {
                "campaigns": len(plan.campaigns),
                "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 podstawowych ustawien.")
    if show_navigation:
        print_next_navigation(client_config.domain)
