"""Shared helpers for CLI commands."""

from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING

import typer
from rich.console import Console

if TYPE_CHECKING:
    from collections.abc import Coroutine
    from typing import Any

    from core.workspace import WorkspaceInfo

# Consoles: ``err`` writes to stderr (status messages), ``out`` to stdout.
err = Console(stderr=True)
out = Console()


def run_async[T](coro: Coroutine[Any, Any, T]) -> T:
    """Run an async coroutine from synchronous CLI code."""
    return asyncio.run(coro)


def load_workspace_or_exit(root: str = ".") -> WorkspaceInfo:
    """Load the workspace, aborting with a friendly message on failure."""
    import albusos

    try:
        return albusos.load_workspace(root)
    except FileNotFoundError as exc:
        err.print(f"[red]Error:[/red] {exc}")
        raise typer.Exit(1) from None
    except RuntimeError as exc:
        err.print(f"[red]Error:[/red] {exc}")
        raise typer.Exit(1) from None
