"""Real default Telegram bootstrap regressions for weekly reminders."""

from __future__ import annotations

from datetime import date, datetime
from pathlib import Path

import pytest

from checkin_cli.weekly_operations_schedule_host_models_r4 import CustomerScheduleTask
from gateway.config import PlatformConfig
from gateway.platforms.nutrition_coaching import NutritionCoachingCoordinator
from gateway.platforms.nutrition_weekly_operations_config import JsonValue
from gateway.platforms.nutrition_weekly_reminder_owner_factory import (
    WeeklyReminderProductionInput,
)
from gateway.platforms.nutrition_weekly_reminder_bootstrap import (
    WeeklyReminderStartupAuthorityIncident,
)
from gateway.platforms.telegram import TelegramAdapter
from gateway.platforms.telegram_weekly_reminder import send_weekly_operations_task
from tests.gateway._nutrition_weekly_reminder_support import (
    CANDIDATE,
    KST,
    FakeTelegramHost,
    ReminderOwnerCoordinator,
    reminder_owner_fixture,
)


def _platform_config(root: Path, extra: dict[str, JsonValue]) -> PlatformConfig:
    configured = dict(extra)
    raw_nutrition = configured["nutrition_coaching"]
    assert isinstance(raw_nutrition, dict)
    nutrition: dict[str, JsonValue] = dict(raw_nutrition)
    nutrition.update(
        {
            "enabled": True,
            "profile_root": str(root),
            "registry_path": "registry.json",
            "weekly_operations_authority_path": "weekly-authority",
        }
    )
    configured["nutrition_coaching"] = nutrition
    return PlatformConfig(enabled=True, token="fixture", extra=configured)


def _bytes(root: Path) -> dict[str, bytes]:
    return {
        str(path.relative_to(root)): path.read_bytes()
        for path in root.rglob("*")
        if path.is_file()
    }


@pytest.mark.asyncio
async def test_default_adapter_bootstrap_opens_existing_capabilities_and_sends_once(
    tmp_path: Path,
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    before = _bytes(tmp_path)
    adapter = TelegramAdapter(_platform_config(tmp_path, fixture.extra))
    assert _bytes(tmp_path) == before
    production = WeeklyReminderProductionInput(
        fixture.extra,
        CANDIDATE,
        fixture.registry,
        fixture.registry_path,
        adapter.weekly_reminder_customers,
    )
    production_coordinator = NutritionCoachingCoordinator(
        tmp_path,
        fixture.registry,
        registry_path=fixture.registry_path,
        task26_candidate_digest=CANDIDATE,
        weekly_reminder_owner_input=production,
    )
    coordinator = ReminderOwnerCoordinator(
        production_coordinator.weekly_reminder_authority_owner, fixture.registry
    )
    host = FakeTelegramHost()
    result = await send_weekly_operations_task(
        host,
        coordinator,
        CustomerScheduleTask("client_001", "reminder", date(2026, 8, 17)),
        local_now=datetime(2026, 8, 17, 20, tzinfo=KST),
    )
    assert result is None
    assert host.calls == 1
    assert coordinator.weekly_reminder_authority_owner is not None
    coordinator.weekly_reminder_authority_owner.close()
    adapter.close_weekly_reminder_capabilities()
    fixture.owner.close()


@pytest.mark.parametrize("failure", ("missing", "stale"))
def test_default_adapter_bootstrap_fails_typed_before_provider_call(
    tmp_path: Path, failure: str
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    config = _platform_config(tmp_path, fixture.extra)
    owner_closed = failure == "missing"
    if owner_closed:
        fixture.owner.close()
        _ = (tmp_path / "data" / ".scheduled-deliveries.lock").unlink()
    else:
        _ = fixture.registry_path.write_text("{}", encoding="utf-8")
    host = FakeTelegramHost()
    with pytest.raises(WeeklyReminderStartupAuthorityIncident):
        _ = TelegramAdapter(config)
    assert host.calls == 0
    if not owner_closed:
        fixture.owner.close()


def test_default_adapter_off_is_inert_without_profile_root() -> None:
    adapter = TelegramAdapter(PlatformConfig(enabled=True, token="fixture", extra={}))
    assert adapter.weekly_reminder_customers == ()
