#
#   Imandra Inc.
#   
#   speclogician/demos/runner.py
#

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Optional
from contextlib import nullcontext

from rich.console import Console
from rich.status import Status

from speclogician.state.state import State


@dataclass(frozen=True)
class DemoRunResult:
    state: State


def apply_demo_changes(
    *,
    changes: list[Any],
    console: Console,
    initial_state: Optional[State] = None,
    show_progress: bool = True,
) -> DemoRunResult:
    """
    Apply an ordered list of StateChange objects to a State.
    """
    state = initial_state or State()

    if show_progress:
        status_ctx = Status(
            "[bold cyan]Applying demo changes…[/bold cyan]",
            console=console,
            spinner="dots",
        )
    else:
        status_ctx = nullcontext()  # type: ignore[name-defined]

    with status_ctx:
        for i, ch in enumerate(changes, start=1):
            if show_progress:
                status_ctx.update(f"[bold cyan]Applying change {i}/{len(changes)}:[/bold cyan] {ch.short_str()}")
            state.process_change(ch, json_only=False)

    return DemoRunResult(state=state)