"""Plan and repair Azure snapshots without calling the acquisition API."""

from __future__ import annotations

from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import date, timedelta
from typing import Literal

Stage = Literal["USAGE", "FOCUS", "GOLD"]
BATCH_KEYS: dict[Stage, str] = {
    "USAGE": "azure.sponsorship.usage.silver.daily",
    "FOCUS": "azure.sponsorship.focus.daily",
    "GOLD": "azure.sponsorship.usage.gold.daily",
}


@dataclass(frozen=True, slots=True)
class ReconciliationState:
    revisions: Mapping[date, Mapping[str, int]]
    # Historical AND current acquisition-to-consumption relationships.
    relationships: Mapping[date, set[date]]
    materialized: Mapping[date, int]

    def targets(self, day: date) -> set[date]:
        return {day, *self.relationships.get(day, set())}

    def usage_valid(self, day: date) -> bool:
        rev = self.revisions.get(day, {})
        return "BRONZE" in rev and rev.get("USAGE", -1) >= rev["BRONZE"]

    def focus_valid(self, day: date) -> bool:
        rev = self.revisions.get(day, {})
        return self.usage_valid(day) and rev.get("FOCUS", -1) >= rev["USAGE"]

    def contributors(self, targets: set[date]) -> set[date]:
        # Match SnapshotGoldExtractor, including empty and historical sources.
        return {
            day
            for day in self.revisions.keys() | self.relationships.keys()
            if self.relationships.get(day, set()) & targets
            or (
                day in targets
                and any(
                    stage in self.revisions.get(day, {})
                    for stage in ("BRONZE", "USAGE", "FOCUS")
                )
            )
        }

    def gold_blockers(self, day: date) -> set[date]:
        return {
            source
            for source in self.contributors(self.targets(day)) | {day}
            if not self.focus_valid(source)
        }

    def gold_needed(self, day: date) -> bool:
        for target in self.targets(day):
            contributors = self.contributors({target}) | {day}
            if any(not self.focus_valid(source) for source in contributors):
                return True
            watermark = self.materialized.get(target, -1)
            if any(
                self.revisions[source]["FOCUS"] > watermark for source in contributors
            ):
                return True
        return False


@dataclass(frozen=True, slots=True)
class ReconciliationPlan:
    missing_bronze: tuple[date, ...]
    usage: tuple[date, ...]
    focus: tuple[date, ...]
    gold: tuple[date, ...]
    gold_blocked: Mapping[date, set[date]] = field(default_factory=dict)

    @property
    def pending(self) -> bool:
        return bool(self.missing_bronze or self.usage or self.focus or self.gold)


def build_plan(
    state: ReconciliationState,
    start: date | None = None,
    end: date | None = None,
) -> ReconciliationPlan:
    if (start is None) != (end is None):
        raise ValueError("--from et --to doivent etre fournis ensemble.")
    if start is not None and end is not None:
        if end < start:
            raise ValueError("--to doit etre superieure ou egale a --from.")
        days = [start + timedelta(days=i) for i in range((end - start).days + 1)]
    else:
        days = sorted(state.revisions.keys() | state.relationships.keys())
    missing = tuple(day for day in days if "BRONZE" not in state.revisions.get(day, {}))
    acquired = [day for day in days if day not in missing]
    gold = tuple(day for day in acquired if state.gold_needed(day))
    return ReconciliationPlan(
        missing_bronze=missing,
        usage=tuple(day for day in acquired if not state.usage_valid(day)),
        focus=tuple(day for day in acquired if not state.focus_valid(day)),
        gold=gold,
        gold_blocked={
            day: blockers for day in gold if (blockers := state.gold_blockers(day))
        },
    )


@dataclass(frozen=True, slots=True)
class ReconciliationResult:
    initial: ReconciliationPlan
    remaining: ReconciliationPlan
    succeeded: tuple[str, ...]
    failed: tuple[str, ...]


def reconcile(
    read_state: Callable[[], ReconciliationState],
    execute: Callable[[Stage, date], bool],
    *,
    start: date | None = None,
    end: date | None = None,
    apply: bool = False,
) -> ReconciliationResult:
    """One bounded pass per stage. A later invocation can resume failures."""
    initial = build_plan(read_state(), start, end)
    if not apply:
        return ReconciliationResult(initial, initial, (), ())
    succeeded: list[str] = []
    failed: list[str] = []

    def run(stage: Stage, day: date) -> None:
        key = f"{BATCH_KEYS[stage]}@{day.isoformat()}"
        (succeeded if execute(stage, day) else failed).append(key)

    for day in initial.usage:
        state = read_state()
        if not state.usage_valid(day) and "BRONZE" in state.revisions.get(day, {}):
            run("USAGE", day)
    for day in build_plan(read_state(), start, end).focus:
        state = read_state()
        if state.usage_valid(day) and not state.focus_valid(day):
            run("FOCUS", day)
    for day in build_plan(read_state(), start, end).gold:
        # Another trigger may already have materialized overlapping usage dates.
        state = read_state()
        if state.gold_needed(day) and not state.gold_blockers(day):
            run("GOLD", day)
    return ReconciliationResult(
        initial,
        build_plan(read_state(), start, end),
        tuple(succeeded),
        tuple(failed),
    )
