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_ad_schedules"
TASK_NAME = "Sprawdzenie harmonogramu reklam"


SCOPE = [
    {
        "area": "Harmonogram 24/7",
        "check": "Oznacz kampanie bez jawnego harmonogramu jako dzialajace caly tydzien i caly dzien.",
    },
    {
        "area": "Niestandardowe godziny",
        "check": "Wypisz kampanie z ustawionymi przedzialami dni i godzin emisji.",
    },
    {
        "area": "Typ kampanii",
        "check": "Pokaz harmonogram razem z typem kampanii, zeby osobno oceniac Search, Shopping i PMax.",
    },
    {
        "area": "Audyt ustawien",
        "check": "Przygotuj szybki przeglad harmonogramow, ktory mozna wykonywac rzadziej niz budzety i anomalie.",
    },
]


OUT_OF_SCOPE = [
    "budzety i wykorzystanie budzetu",
    "strategie stawek oraz cele Docelowy ROAS/Docelowy CPA",
    "zapytania uzytkownikow oraz wykluczenia",
    "reklamy RSA, assety i kreacje",
    "wdrazanie zmian harmonogramu na koncie Google Ads",
]


DAY_ORDER = {
    "MONDAY": 1,
    "TUESDAY": 2,
    "WEDNESDAY": 3,
    "THURSDAY": 4,
    "FRIDAY": 5,
    "SATURDAY": 6,
    "SUNDAY": 7,
}


DAY_LABELS = {
    "MONDAY": "poniedzialek",
    "TUESDAY": "wtorek",
    "WEDNESDAY": "sroda",
    "THURSDAY": "czwartek",
    "FRIDAY": "piatek",
    "SATURDAY": "sobota",
    "SUNDAY": "niedziela",
}


MINUTE_LABELS = {
    "ZERO": "00",
    "FIFTEEN": "15",
    "THIRTY": "30",
    "FORTY_FIVE": "45",
}


@dataclass
class AdSchedulePlan:
    campaigns: list[dict]
    schedule_summary: list[dict]
    channel_summary: 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,
            "schedule_summary": self.schedule_summary,
            "channel_summary": self.channel_summary,
            "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) -> "AdSchedulePlan":
        return cls(
            campaigns=data.get("campaigns", []),
            schedule_summary=data.get("schedule_summary", []),
            channel_summary=data.get("channel_summary", []),
            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 minute_label(value: Any) -> str:
    raw = enum_name(value)
    return MINUTE_LABELS.get(raw, raw)


def hour_label(hour: int, minute: str) -> str:
    return f"{int(hour):02d}:{minute}"


def schedule_label(schedule: dict) -> str:
    day = DAY_LABELS.get(schedule["day_of_week"], schedule["day_of_week"])
    start = hour_label(schedule["start_hour"], schedule["start_minute"])
    end = hour_label(schedule["end_hour"], schedule["end_minute"])
    return f"{day} {start}-{end}"


def join_schedule_labels(schedules: list[dict], limit: int = 8) -> str:
    if not schedules:
        return "24/7 (brak jawnego harmonogramu)"
    labels = [schedule["label"] for schedule in schedules]
    shown = labels[:limit]
    if len(labels) > limit:
        shown.append(f"... +{len(labels) - limit}")
    return ", ".join(shown)


def campaign_flags(campaign: dict) -> list[str]:
    schedules = campaign["schedules"]
    flags = []
    if not schedules:
        flags.append("dziala 24/7")
    if len(schedules) == 7 and all(
        item["start_hour"] == 0
        and item["start_minute"] == "00"
        and item["end_hour"] == 24
        and item["end_minute"] == "00"
        for item in schedules
    ):
        flags.append("harmonogram rowny 24/7")
    if schedules and len(schedules) < 5:
        flags.append("malo dni emisji")
    if any(item["start_hour"] < 6 or item["end_hour"] > 22 for item in schedules):
        flags.append("emisja nocna do oceny")
    return flags or ["ok"]


def fetch_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
        FROM campaign
        WHERE campaign.status != 'REMOVED'
        """,
    )

    campaigns = []
    for row in rows:
        campaign = row.campaign
        campaigns.append(
            {
                "campaign_id": str(campaign.id),
                "campaign_name": campaign.name,
                "status": enum_name(campaign.status),
                "channel_type": enum_name(campaign.advertising_channel_type),
                "schedules": [],
            }
        )
    return campaigns


def fetch_ad_schedules(client_config: ClientConfig) -> dict[str, 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_criterion.criterion_id,
          campaign_criterion.status,
          campaign_criterion.ad_schedule.day_of_week,
          campaign_criterion.ad_schedule.start_hour,
          campaign_criterion.ad_schedule.start_minute,
          campaign_criterion.ad_schedule.end_hour,
          campaign_criterion.ad_schedule.end_minute
        FROM campaign_criterion
        WHERE campaign.status != 'REMOVED'
          AND campaign_criterion.status != 'REMOVED'
          AND campaign_criterion.type = 'AD_SCHEDULE'
        """,
    )

    schedules_by_campaign: dict[str, list[dict]] = {}
    for row in rows:
        campaign_id = str(row.campaign.id)
        criterion = row.campaign_criterion
        schedule = criterion.ad_schedule
        record = {
            "criterion_id": str(criterion.criterion_id),
            "status": enum_name(criterion.status),
            "day_of_week": enum_name(schedule.day_of_week),
            "start_hour": int(schedule.start_hour or 0),
            "start_minute": minute_label(schedule.start_minute),
            "end_hour": int(schedule.end_hour or 0),
            "end_minute": minute_label(schedule.end_minute),
        }
        record["label"] = schedule_label(record)
        schedules_by_campaign.setdefault(campaign_id, []).append(record)

    for schedules in schedules_by_campaign.values():
        schedules.sort(key=lambda item: (DAY_ORDER.get(item["day_of_week"], 99), item["start_hour"], item["start_minute"]))
    return schedules_by_campaign


def attach_schedules(campaigns: list[dict], schedules_by_campaign: dict[str, list[dict]]) -> list[dict]:
    for campaign in campaigns:
        campaign["schedules"] = schedules_by_campaign.get(campaign["campaign_id"], [])
        campaign["schedule_count"] = len(campaign["schedules"])
        campaign["schedule_label"] = join_schedule_labels(campaign["schedules"])
        campaign["flags"] = campaign_flags(campaign)
    campaigns.sort(key=lambda row: (row["channel_type"], row["campaign_name"]))
    return campaigns


def build_schedule_summary(campaigns: list[dict]) -> list[dict]:
    return [
        {
            "metric": "Kampanie",
            "count": len(campaigns),
        },
        {
            "metric": "Kampanie bez jawnego harmonogramu",
            "count": sum(1 for campaign in campaigns if campaign["schedule_count"] == 0),
        },
        {
            "metric": "Kampanie z harmonogramem",
            "count": sum(1 for campaign in campaigns if campaign["schedule_count"] > 0),
        },
        {
            "metric": "Kampanie z emisja nocna do oceny",
            "count": sum(1 for campaign in campaigns if "emisja nocna do oceny" in campaign["flags"]),
        },
        {
            "metric": "Kampanie z malą liczba dni emisji",
            "count": sum(1 for campaign in campaigns if "malo dni emisji" in campaign["flags"]),
        },
    ]


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


def build_ad_schedule_plan(client_config: ClientConfig) -> AdSchedulePlan:
    warnings = []
    try:
        campaigns = fetch_campaigns(client_config)
        schedules_by_campaign = fetch_ad_schedules(client_config)
        campaigns = attach_schedules(campaigns, schedules_by_campaign)
    except Exception as exc:
        campaigns = []
        warnings.append(f"Nie udalo sie pobrac harmonogramow reklam z Google Ads API: {exc}")

    if not campaigns:
        warnings.append("Nie znaleziono kampanii albo nie udalo sie pobrac harmonogramow.")

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

    return AdSchedulePlan(
        campaigns=campaigns,
        schedule_summary=build_schedule_summary(campaigns),
        channel_summary=build_channel_summary(campaigns),
        scope=SCOPE,
        out_of_scope=OUT_OF_SCOPE,
        knowledge_rules=knowledge_rules,
        warnings=warnings,
    )


def save_ad_schedule_plan(domain: str, plan: AdSchedulePlan) -> 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 harmonogramu reklam",
        "",
        f"Klient: {domain}",
        f"Utworzono: {ts.isoformat(timespec='seconds')}",
        "",
        "## Podsumowanie",
        "",
        f"- Kampanie: {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"| {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.schedule_summary:
        lines.extend(["## Podsumowanie harmonogramow", "", "| Metryka | Liczba |", "| --- | --- |"])
        for row in plan.schedule_summary:
            lines.append(f"| {md_cell(row['metric'])} | {row['count']} |")
        lines.append("")
    if plan.channel_summary:
        lines.extend(["## Podsumowanie po typach kampanii", "", "| Typ | Liczba |", "| --- | --- |"])
        for row in plan.channel_summary:
            lines.append(f"| {row['channel_type']} | {row['count']} |")
        lines.append("")
    if plan.campaigns:
        lines.extend(
            [
                "## Kampanie",
                "",
                "| Kampania | Typ | Status | Harmonogram | Flagi |",
                "| --- | --- | --- | --- | --- |",
            ]
        )
        for campaign in plan.campaigns:
            lines.append(
                f"| {md_cell(campaign['campaign_name'])} | {campaign['channel_type']} | {campaign['status']} | "
                f"{md_cell(campaign['schedule_label'])} | {md_cell(', '.join(campaign['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_ad_schedule_plan(plan: AdSchedulePlan) -> None:
    print("\nPlan sprawdzenia harmonogramu reklam")
    print_table(
        ["Metryka", "Liczba"],
        [
            ["Kampanie", 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.schedule_summary:
        print("\nPodsumowanie harmonogramow")
        print_table(["Metryka", "Liczba"], [[row["metric"], str(row["count"])] for row in plan.schedule_summary])
    if plan.channel_summary:
        print("\nPodsumowanie po typach kampanii")
        print_table(
            ["Typ", "Liczba"],
            [[row["channel_type"], str(row["count"])] for row in plan.channel_summary],
        )
    if plan.campaigns:
        print("\nKampanie")
        print_table(
            ["Nr", "Kampania", "Typ", "Liczba przedz.", "Harmonogram", "Flagi"],
            [
                [
                    str(index),
                    campaign["campaign_name"],
                    campaign["channel_type"],
                    str(campaign["schedule_count"]),
                    campaign["schedule_label"],
                    ", ".join(campaign["flags"]),
                ]
                for index, campaign in enumerate(plan.campaigns[:30], 1)
            ],
        )
        if len(plan.campaigns) > 30:
            print(f"... oraz {len(plan.campaigns) - 30} kolejnych kampanii 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_ad_schedule_plan(
    client_config: ClientConfig,
    plan: AdSchedulePlan,
    show_navigation: bool = True,
) -> None:
    print("\nTo zadanie jest audytem harmonogramu reklam 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_ad_schedules(
    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 = AdSchedulePlan.from_dict(plan_data)
        print_ad_schedule_plan(plan)
        apply_ad_schedule_plan(client_config, plan, show_navigation=show_navigation)
        return

    print(f"\nKlient: {client_config.domain}")
    print("Przygotowuje plan sprawdzenia harmonogramu reklam...")
    plan = build_ad_schedule_plan(client_config)
    print_ad_schedule_plan(plan)
    json_path, md_path = save_ad_schedule_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 harmonogramu reklam.")
    if show_navigation:
        print_next_navigation(client_config.domain)
