"""
Helper functions to emit and link prophecy receipts (prophecy → snapshot → outcome).
"""
from __future__ import annotations

from datetime import datetime, timezone
from typing import Optional

from receipts.domains.prophecy import (
    ProphecyReceipt,
    ProphecyFutureSnapshotReceipt,
    ProphecyOutcomeReceipt,
)
from receipts.domains.prophecy import _normalize_ts


def emit_future_snapshot_for_prophecy(
    prophecy: ProphecyReceipt,
    *,
    snapshot_id: Optional[str] = None,
    target_window_start: Optional[datetime] = None,
    target_window_end: Optional[datetime] = None,
) -> ProphecyFutureSnapshotReceipt:
    """
    Build a ProphecyFutureSnapshotReceipt alongside a ProphecyReceipt.

    Caller is responsible for persisting via the standard receipt writer.
    """
    ts_now = _normalize_ts(datetime.now(timezone.utc))

    snapshot_id = snapshot_id or f"fs_{prophecy.prophecy_id}"
    tw_start = _normalize_ts(target_window_start) or ts_now
    tw_end = _normalize_ts(target_window_end) or ts_now

    return ProphecyFutureSnapshotReceipt(
        receipt_id=f"pfs_{snapshot_id}",
        snapshot_id=snapshot_id,
        prophecy_id=prophecy.prophecy_id,
        plan_id=prophecy.plan_id,
        operation_domain=prophecy.operation_domain,
        operation_type=prophecy.operation_type,
        target_window_start=tw_start,
        target_window_end=tw_end,
        projected_success_rate=prophecy.expected_success_rate,
        projected_value=prophecy.expected_value,
        projected_roi=prophecy.expected_roi,
        projected_risk_level=prophecy.risk_level,
        projected_coherence_band=prophecy.coherence_band,
        key_assumptions=prophecy.risk_notes or [],
        regime_shift_warning=False,
        regime_shift_notes=[],
        parent_ids=[prophecy.receipt_id],
        ts=ts_now,
    )


def link_outcome_to_snapshot(
    outcome: ProphecyOutcomeReceipt,
    snapshot: ProphecyFutureSnapshotReceipt,
    *,
    snapshot_held: Optional[bool] = None,
    deviation_notes: Optional[list[str]] = None,
) -> ProphecyFutureSnapshotReceipt:
    """
    Return a copy of the snapshot with outcome linkage/evaluation filled.
    """
    deviation_notes = deviation_notes or []
    return snapshot.model_copy(
        update={
            "outcome_id": outcome.receipt_id,
            "snapshot_held": snapshot_held,
            "snapshot_deviation_notes": deviation_notes,
        }
    )
