from __future__ import annotations

import typer

from dattos_cli import __version__
from dattos_sdk import ApiError, DattosClient
from dattos_sdk.config import ConfigError, get_config, set_profile_override
from dattos_cli.output import is_tty, print_error, print_json

app = typer.Typer(
    name="dattos",
    help="CLI for the Dattos platform.",
)


@app.callback(invoke_without_command=True)
def main(
    ctx: typer.Context,
    profile: str = typer.Option(None, "--profile", "-p", help="Use a named profile.", envvar="DATTOS_PROFILE"),
):
    """CLI for the Dattos platform."""
    if profile:
        set_profile_override(profile)
    if ctx.invoked_subcommand is None:
        if is_tty():
            from dattos_cli.banner import print_banner
            print_banner()
            typer.echo(ctx.get_help())
        else:
            typer.echo(ctx.get_help())
        raise typer.Exit(0)


def get_client(folder_id: str | None = None) -> DattosClient:
    """Create an authenticated DattosClient from config.

    Args:
        folder_id: Override folder ID. Falls back to DATTOS_FOLDER_ID env var / config file.
    """
    try:
        cfg = get_config()
    except ConfigError as e:
        print_error("config_error", str(e), 2)
        raise typer.Exit(2)
    from dattos_sdk.config import CONFIG_DIR, get_active_profile
    cache_dir = CONFIG_DIR / "cache" / get_active_profile()
    return DattosClient(
        base_url=cfg.api_url,
        api_key=cfg.api_key,
        folder_id=folder_id or cfg.folder_id,
        cache_dir=cache_dir,
    )


def handle_api_error(e: ApiError) -> None:
    """Print API error to stderr and exit."""
    error_type = {
        401: "auth_error",
        403: "forbidden",
        404: "not_found",
        429: "rate_limited",
    }.get(e.status_code, "api_error")
    exit_code = 2 if e.status_code in (401, 403) else 1
    print_error(error_type, e.detail, e.status_code)
    raise typer.Exit(exit_code)


@app.command()
def version():
    """Print the CLI version."""
    if is_tty():
        from dattos_cli.banner import print_banner
        print_banner()
    else:
        print_json({"version": __version__})


from dattos_cli.commands import config_cmd, analyses, loads, datasets, matching, reports, folders, workflows, imports, etl, users, mcp_cmd, doctor, auth_cmd, connectors, config_packs, cache_cmd, batch

app.add_typer(config_cmd.app, name="config")
app.add_typer(analyses.app, name="analyses")
app.add_typer(loads.app, name="loads")
app.add_typer(datasets.app, name="datasets")
app.add_typer(matching.app, name="matching")
app.add_typer(reports.app, name="reports")
app.add_typer(folders.app, name="folders")
app.add_typer(workflows.app, name="workflows")
app.add_typer(imports.app, name="imports")
app.add_typer(etl.app, name="etl")
app.add_typer(users.app, name="users")
app.add_typer(mcp_cmd.app, name="mcp")
app.add_typer(doctor.app, name="doctor")
app.add_typer(auth_cmd.app, name="auth")
app.add_typer(connectors.app, name="connectors")
app.add_typer(config_packs.app, name="config-packs")
app.add_typer(cache_cmd.app, name="cache")
app.add_typer(batch.app, name="batch")
