"""Production dispatcher invocation regression."""

from __future__ import annotations

from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

import checkin_cli
import pytest

from checkin_cli.weekly_operations_layout import customer_data_name
from tests.gateway._nutrition_weekly_dispatcher_cases import dispatcher_fixture


@pytest.mark.asyncio
async def test_authorized_tick_dispatches_enabled_weekly_operations_before_generic_work(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
    fixture = dispatcher_fixture(tmp_path, "cutoff")
    fixture.install_due(monkeypatch)

    result = await fixture.host.run_authorized(
        datetime(2026, 8, 17, 23, tzinfo=ZoneInfo("Asia/Seoul"))
    )

    assert result.success is True
    assert len(fixture.reminder.store.read()) == 1
    assert len(fixture.provider.calls) == 1


@pytest.mark.asyncio
async def test_monday_tick_initializes_missing_weekly_sidecar(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
    fixture = dispatcher_fixture(tmp_path, "cutoff")
    sidecar = (
        fixture.reminder.store.authority.observed_path
        / customer_data_name(fixture.reminder.store.customer_identity_digest)
    )
    assert not sidecar.exists()

    def no_due(*_args: object, **_kwargs: object) -> tuple[()]:
        return ()

    monkeypatch.setattr(checkin_cli, "build_due_customer_tasks", no_due)
    fence = checkin_cli.initialize_schedule_delivery_fence(tmp_path)
    assert fence.state == "ready"
    fixture.coordinator.weekly_session = None

    result = await fixture.host.run_authorized(
        datetime(2026, 8, 17, 23, tzinfo=ZoneInfo("Asia/Seoul"))
    )

    assert result.success is True
    assert sidecar.is_file()
    assert sidecar.stat().st_mode & 0o777 == 0o600
    assert fixture.coordinator.drafts == {}
