"""23:00 missed transition joined to durable reminder evidence."""

from __future__ import annotations

from dataclasses import dataclass, replace
from enum import StrEnum
from typing import Final, Never, assert_never
from zoneinfo import ZoneInfo

from .weekly_operations_schedule_host_models_r4 import ScheduledDeliveryReceipt
from .weekly_reminder_schedule import receipts
from .weekly_operations import ReminderIdentity, WeeklyOperationInput, WeeklyOperationRow
from .weekly_operations_correlation import (
    CorrelationAction,
    CorrelationOutcome,
    CorrelationProjection,
    CorrelationProjectionInput,
    CorrelationScope,
    project_canonical_checkin,
)
from .weekly_reminder_authority import WeeklyReminderRequest

_KST: Final = ZoneInfo("Asia/Seoul")


class CutoffClassification(StrEnum):
    NOT_DUE = "not_due"
    INACTIVE = "inactive"
    ANSWERED = "answered"
    REMINDED_NO_RESPONSE = "reminded_no_response"
    REMINDER_DELIVERY_INCIDENT = "reminder_delivery_incident"
    REPLAY = "replay"


@dataclass(frozen=True, slots=True)
class CutoffResult:
    classification: CutoffClassification
    appended: bool


def _reminder(request: WeeklyReminderRequest) -> ScheduledDeliveryReceipt | None:
    matches = tuple(
        receipt
        for receipt in receipts(request.bound_customer)
        if receipt.customer_key == request.bound_customer.customer_identity_digest
        and receipt.kst_day == request.kst_day
        and receipt.kind == "reminder"
    )
    if len(matches) > 1:
        raise AssertionError("schedule authority admitted multiple reminder lineages")
    return matches[0] if matches else None


def _correlation_variant(value: CorrelationOutcome) -> CorrelationOutcome | str:
    return value


def _invalid_outcome(value: str) -> Never:
    raise AssertionError(f"invalid correlation outcome: {value}")


def run_missed_cutoff(request: WeeklyReminderRequest) -> CutoffResult:
    """Append missed independently and classify its reminder evidence."""
    if request.now.tzinfo is None or request.now.utcoffset() is None:
        raise AssertionError("weekly cutoff time is naive")
    if request.now.astimezone(_KST).hour < 23:
        return CutoffResult(CutoffClassification.NOT_DUE, False)
    reminder = _reminder(request)
    with request.bound_customer.source.read_locked() as snapshot:

        def decide(rows: tuple[WeeklyOperationRow, ...]) -> tuple[WeeklyOperationInput | None, CorrelationProjection]:
            projection = project_canonical_checkin(
                CorrelationProjectionInput(
                    CorrelationScope(
                        request.bound_customer.customer_identity_digest,
                        request.kst_day,
                        CorrelationAction.CUTOFF,
                    ),
                    snapshot,
                    rows,
                )
            )
            operation = projection.operation
            if operation is not None and reminder is not None and reminder.state == "sent_audited":
                operation = replace(
                    operation,
                    reminder=ReminderIdentity(
                        reminder.reservation_id,
                        f"schedule-row-{reminder.append_sequence}",
                    ),
                )
            return operation, projection

        appended, projection = request.bound_customer.store.transact(decide)
    match _correlation_variant(projection.outcome):
        case CorrelationOutcome.MISSED | CorrelationOutcome.REPLAY:
            pass
        case CorrelationOutcome.SUBMITTED | CorrelationOutcome.LATE_SUBMITTED | CorrelationOutcome.SOURCE_ADVANCED | CorrelationOutcome.AWAITING_CUTOFF:
            return CutoffResult(CutoffClassification.ANSWERED, False)
        case CorrelationOutcome.MISSING | CorrelationOutcome.INVALID_CANONICAL | CorrelationOutcome.INVALID_LINEAGE:
            return CutoffResult(CutoffClassification.REMINDER_DELIVERY_INCIDENT, False)
        case _ as unreachable:
            assert_never(_invalid_outcome(unreachable))
    classification = (
        CutoffClassification.REMINDED_NO_RESPONSE
        if reminder is not None and reminder.state == "sent_audited"
        else CutoffClassification.REMINDER_DELIVERY_INCIDENT
    )
    if appended is None:
        return CutoffResult(CutoffClassification.REPLAY, False)
    return CutoffResult(classification, appended.appended)
