from __future__ import annotations

from dataclasses import replace
from datetime import datetime, timezone
from pathlib import Path

from gateway.platforms.telegram_customer_bootstrap import (
    BootstrapState,
    ConsentHandoff,
    CustomerDraft,
    RecoverySlot,
    RoomBootstrapSession,
    RoomBootstrapStore,
    consent_handoff_digest,
    customer_consent_callback,
    room_bootstrap_state_dir,
)


def awaiting_consent(
    root: Path,
    *,
    bind_receipt: bool = True,
    first_claim: bool = False,
) -> tuple[RoomBootstrapStore, RoomBootstrapSession]:
    store = RoomBootstrapStore(room_bootstrap_state_dir(root))
    prepared = store.prepare_rehearsal_customer_invite(
        CustomerDraft(
            customer_key="customer_001",
            display_name="Customer",
            starts_on="2026-09-01",
            daily_time="08:00",
            weekly_weekday=0,
            monthly_day=1,
            calories_kcal=2200,
            protein_g=140,
            meals=("아침", "점심", "저녁"),
            customer_user_id=None if first_claim else "10",
        ),
        bot_username="nutricoach_kr_bot",
        owner_id="12",
        first_claim=first_claim,
    )
    claimed = store.claim_rehearsal_customer_invite(
        prepared.customer_link.rsplit("=", 1)[1],
        user_id="10",
        chat_id="10",
        message_id="100",
    )
    awaiting = store.transition(
        claimed.session_id,
        expected_generation=claimed.generation,
        target=BootstrapState.AWAITING_CONSENT,
    )
    publication = store.reserve_consent_publication(
        awaiting.session_id,
        expected_generation=awaiting.generation,
    )
    attempt = store.reserve_recovery_attempt(
        publication.session_id,
        slot=RecoverySlot.CONSENT_CARD,
        chat_id="10",
        expected_generation=publication.generation,
    )
    if not bind_receipt:
        return store, store.get(publication.session_id)
    receipted = store.bind_recovery_receipt(
        publication.session_id,
        slot=RecoverySlot.CONSENT_CARD,
        chat_id="10",
        attempt_generation=attempt.generation,
        receipt_id="500",
    )
    return store, receipted


def consent_handoff(session: RoomBootstrapSession) -> ConsentHandoff:
    provisional = ConsentHandoff(
        update_id=700,
        actor_id=10,
        chat_id=10,
        topic_id=0,
        message_id=500,
        callback_data=customer_consent_callback(
            "customer_001",
            "privacy-v1",
            "g",
        ),
        bootstrap_generation=session.generation,
        recorded_at=datetime(2026, 8, 31, 8, tzinfo=timezone.utc),
        provenance_digest="",
    )
    return replace(
        provisional,
        provenance_digest=consent_handoff_digest(session, provisional),
    )
