"""Offline startup fence for the installed weekly-reminder candidate."""

from __future__ import annotations

import argparse
import json
import sys
from datetime import UTC, datetime
from pathlib import Path
from typing import cast

import yaml
from pydantic import JsonValue, TypeAdapter

from checkin_cli.customer_coaching import load_customer_registry
from gateway.config import PlatformConfig
from gateway.platforms.nutrition_weekly_reminder_owner_factory import (
    WeeklyReminderProductionInput,
    build_weekly_reminder_authority_owner,
)
from gateway.platforms.telegram import TelegramAdapter

_OBJECT = TypeAdapter(dict[str, JsonValue])


class WeeklyStartupSmokeError(RuntimeError):
    """Installed weekly authority could not be constructed offline."""


def _mapping(value: JsonValue | None, label: str) -> dict[str, JsonValue]:
    if not isinstance(value, dict):
        raise WeeklyStartupSmokeError(label)
    return value


def _platform_config(path: Path) -> PlatformConfig:
    try:
        raw = cast(object, yaml.safe_load(path.read_text(encoding="utf-8")))
        document = _OBJECT.validate_python(raw)
    except (OSError, ValueError, yaml.YAMLError) as error:
        raise WeeklyStartupSmokeError("config") from error
    platforms = _mapping(document.get("platforms"), "platforms")
    telegram = _mapping(platforms.get("telegram"), "telegram")
    extra = _mapping(telegram.get("extra"), "extra")
    return PlatformConfig(enabled=True, token="offline-startup-smoke", extra=extra)


def verify_weekly_startup(
    profile: Path,
    config_path: Path,
    candidate_digest: str,
    *,
    now: datetime | None = None,
) -> tuple[str, ...]:
    """Construct capabilities and tick every enabled customer without I/O."""
    config = _platform_config(config_path)
    registry_path = profile / "customers/registry.json"
    registry = load_customer_registry(registry_path, profile)
    expected = tuple(
        runtime.spec.customer_key
        for runtime in registry.customers
        if runtime.spec.enabled
    )
    adapter = TelegramAdapter(config)
    try:
        actual = tuple(
            customer.runtime.spec.customer_key
            for customer in adapter.weekly_reminder_customers
        )
        if actual != expected:
            raise WeeklyStartupSmokeError("enabled customers")
        production = WeeklyReminderProductionInput(
            config.extra,
            candidate_digest,
            registry,
            registry_path,
            adapter.weekly_reminder_customers,
        )
        owner = build_weekly_reminder_authority_owner(production)
        if owner is None or owner.customer_keys != expected:
            raise WeeklyStartupSmokeError("owner")
        instant = now or datetime.now(UTC)
        for key in expected:
            _ = owner.tick_snapshot(key, instant)
        return expected
    finally:
        adapter.close_weekly_reminder_capabilities()


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    _ = parser.add_argument("--profile", required=True, type=Path)
    _ = parser.add_argument("--config", required=True, type=Path)
    _ = parser.add_argument("--candidate", required=True)
    _ = parser.parse_args()
    profile = Path(sys.argv[sys.argv.index("--profile") + 1])
    config = Path(sys.argv[sys.argv.index("--config") + 1])
    candidate = sys.argv[sys.argv.index("--candidate") + 1]
    enabled = verify_weekly_startup(
        profile,
        config,
        candidate,
    )
    print(json.dumps({"enabled_customer_keys": enabled}, separators=(",", ":")))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
