"""Adapter that invokes the installed WeeklyOperationsStore read/append API."""

from __future__ import annotations

from checkin_cli.weekly_operations import (
    CanonicalPin,
    CustomerIdentityDigest,
    DayState,
    ReminderIdentity,
    SourceLineage,
    WeeklyOperationInput,
)
from checkin_cli.weekly_operations_store import WeeklyOperationsStore

from .store import (
    AppendOutcome,
    ContinuityRow,
    ReissueOperation,
)


class InstalledStoreAdapter:
    """Project the installed store into the sealed narrow contract."""

    def __init__(self, store: WeeklyOperationsStore) -> None:
        self._store: WeeklyOperationsStore = store

    def read(self) -> tuple[ContinuityRow, ...]:
        """Read through the installed shared-lock validated API."""
        return tuple(
            ContinuityRow.model_validate_json(row.model_dump_json()) for row in self._store.read()
        )

    def append(self, operation: ReissueOperation) -> AppendOutcome:
        """Reconstruct typed input and invoke the installed append API."""
        row = operation.row
        source = (
            None
            if row.source_event_id is None
            else SourceLineage(row.source_event_id, row.source_event_digest or "")
        )
        reminder = ReminderIdentity(row.reminder_reservation_id, row.reminder_audit_id)
        result = self._store.append(
            WeeklyOperationInput(
                customer_identity_digest=CustomerIdentityDigest(row.customer_identity_digest),
                kst_day=row.kst_day,
                state=DayState(row.state),
                canonical=CanonicalPin(row.canonical_sequence, row.canonical_digest),
                occurred_at=row.occurred_at_kst,
                source=source,
                reminder=reminder,
            )
        )
        projected = ContinuityRow.model_validate_json(result.row.model_dump_json())
        return AppendOutcome(projected, result.appended)
