from __future__ import annotations

import typer
from rich.console import Console

from .client import UforiaApiClient
from .commands import app as commands_app
from .config import OutputMode, TerminalConfig
from .state import TerminalState

app = commands_app


@app.callback()
def main(
    ctx: typer.Context,
    api_base_url: str | None = typer.Option(None, "--api-base-url", envvar="UFORIA_API_BASE_URL"),
    timeout: float | None = typer.Option(None, "--timeout", envvar="UFORIA_TIMEOUT_SECONDS"),
    output: OutputMode | None = typer.Option(None, "--output"),
    json_mode: bool = typer.Option(False, "--json", help="Emit a single JSON payload."),
    ndjson_mode: bool = typer.Option(False, "--ndjson", help="Emit newline-delimited JSON rows."),
    compact: bool = typer.Option(False, "--compact"),
) -> None:
    if json_mode and ndjson_mode:
        raise typer.BadParameter("Use only one of --json or --ndjson")
    selected_output = output.value if output else None
    if json_mode:
        selected_output = OutputMode.JSON.value
    if ndjson_mode:
        selected_output = OutputMode.NDJSON.value
    config = TerminalConfig.from_values(api_base_url, timeout, selected_output, compact)
    ctx.obj = TerminalState(
        config=config,
        client=UforiaApiClient(config.api_base_url, config.timeout_seconds),
        console=Console(),
    )
