"""Demo command implementation for the ICSD CLI."""

from __future__ import annotations

from pathlib import Path

from icsd.core.invariants import Invariant, InvariantSet
from icsd.core.transition import Transition

from ._shared import EXIT_OK, EXIT_TOOL_ERROR, emit_stderr, emit_stdout

DEFAULT_DEMO_OUTPUT = "quickstart.evidence.json"
DEMO_TRANSITION_ID = "11111111-1111-4111-8111-111111110084"
DEMO_TIMESTAMP = "2026-03-03T00:00:00Z"


def build_demo_evidence_json() -> str:
    """Build the deterministic quick-start evidence payload."""
    transition = Transition.simple(
        name="debit_demo",
        mutate=lambda state: state.update({"balance": state["balance"] - 1}),
        invariants=InvariantSet(
            [Invariant(name="balance_non_negative", check=lambda state: state["balance"] >= 0)]
        ),
    )
    result = transition.apply(
        state={"balance": 10},
        entity_type="account",
        entity_id="acct-001",
        actor="user:quickstart",
        authority="policy/account-demo",
        transition_id=DEMO_TRANSITION_ID,
        timestamp=DEMO_TIMESTAMP,
    )
    return result.evidence_json


def run_demo(output: str) -> int:
    """Run the demo command."""
    output_path = Path(output)
    try:
        output_path.write_text(build_demo_evidence_json(), encoding="utf-8")
    except OSError as exc:
        emit_stderr(f"demo: unable to write {output_path}: {exc}.")
        return EXIT_TOOL_ERROR
    emit_stdout(f"demo: wrote deterministic evidence to {output_path}.")
    return EXIT_OK
