"""Shared helpers for session-hub-cli commands."""

from __future__ import annotations

import json
import os
from datetime import datetime
from typing import Any

import typer
from rich.console import Console

from session_hub_core import DatabaseConfig, QueryAPI


def get_engine_config(console: Console) -> DatabaseConfig:
    """Build DatabaseConfig from env, exiting with a clear error if SESSION_HUB_DSN is unset."""
    if not os.environ.get("SESSION_HUB_DSN"):
        console.print("[red]Error:[/red] SESSION_HUB_DSN environment variable is required")
        raise typer.Exit(1) from None
    try:
        return DatabaseConfig.from_env()
    except ValueError as exc:
        console.print(f"[red]Error:[/red] {exc}")
        raise typer.Exit(1) from None


def get_query_api(console: Console) -> QueryAPI:
    """Create a QueryAPI instance from environment configuration."""
    return QueryAPI(get_engine_config(console))


def fmt_datetime(dt: datetime | None) -> str:
    """Format a datetime for CLI display."""
    return dt.strftime("%Y-%m-%d %H:%M") if dt else "-"


def print_json(console: Console, data: Any) -> None:
    """Print data as indented JSON."""
    console.print(json.dumps(data, indent=2), markup=False)
