"""Typed due-task planning for the weekly Telegram host."""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Protocol, runtime_checkable

from gateway.platforms.telegram_weekly_host_capabilities import (
    TelegramWeeklyHostError,
)

if TYPE_CHECKING:
    from checkin_cli.customer_coaching import CustomerRegistry
    from checkin_cli.weekly_operations_schedule_host_models_r4 import (
        WeeklyOperationsSchedulePolicy,
    )
    from gateway.platforms.nutrition_weekly_dispatcher import WeeklyOperationsTask


@runtime_checkable
class WeeklyPlanningCoordinator(Protocol):
    @property
    def registry(self) -> CustomerRegistry: ...


@dataclass(frozen=True, slots=True)
class WeeklySchedulePlan:
    policy: WeeklyOperationsSchedulePolicy | None
    tasks: Sequence[WeeklyOperationsTask]


class TelegramWeeklyPlanningMixin:
    """Build due tasks with the enabled weekly policy when present."""

    def _get_nutrition_coaching(self) -> WeeklyPlanningCoordinator | None:
        raise NotImplementedError

    def _weekly_operations_schedule_policy(
        self,
    ) -> WeeklyOperationsSchedulePolicy | None:
        raise NotImplementedError

    def _weekly_schedule_plan(self, local_now: datetime) -> WeeklySchedulePlan:
        from checkin_cli import build_due_customer_tasks

        coordinator = self._get_nutrition_coaching()
        if not isinstance(coordinator, WeeklyPlanningCoordinator):
            raise TelegramWeeklyHostError(
                "weekly planning coordinator contract unavailable"
            )
        policy = self._weekly_operations_schedule_policy()
        tasks = (
            build_due_customer_tasks(coordinator.registry, local_now)
            if policy is None
            else build_due_customer_tasks(
                coordinator.registry,
                local_now,
                weekly_operations_policy=policy,
            )
        )
        return WeeklySchedulePlan(policy, tasks)
