from __future__ import annotations

from dataclasses import dataclass

from rich.console import Console
from rich.text import Text


@dataclass
class WaitSpinner:
    """A minimal spinner for "waiting" CLI operations.

    This is intended for operations where we don't have meaningful incremental
    progress to report (e.g. waiting on an async backend operation to complete).

    Usage:
        with WaitSpinner("Creating reasoner...", "Reasoner created!"):
            do_work()
    """

    message: str | Text
    success_message: str | None = None
    failed_message: str | None = None
    spinner: str = "dots"
    console: Console | None = None

    def __post_init__(self) -> None:
        if self.console is None:
            self.console = Console()

    def __enter__(self) -> "WaitSpinner":
        assert self.console is not None
        msg = self.message if isinstance(self.message, Text) else Text(str(self.message), style="green")
        self._status = self.console.status(msg, spinner=self.spinner)
        self._status.__enter__()
        return self

    def __exit__(self, exc_type, exc, tb) -> bool:
        # Stop the status line first to avoid rich Live artifacts.
        status_cm: object | None = getattr(self, "_status", None)
        if status_cm is not None:
            try:
                getattr(status_cm, "__exit__")(exc_type, exc, tb)
            except Exception:
                pass

        assert self.console is not None
        if exc_type is None:
            if self.success_message:
                self.console.print(self.success_message)
            return False

        # Exception path: optionally print a friendly failure line.
        if self.failed_message:
            self.console.print(self.failed_message)
        return False

