"""
Namespaces CLI commands for managing namespaces.

Commands:
- ls: List namespaces the user has access to
"""

from __future__ import annotations

import typer
from rich.console import Console
from rich.table import Table

from terminaluse.core import ApiError
from terminaluse.lib.cli.utils.errors import CLIError

console = Console()
namespaces = typer.Typer(no_args_is_help=True)


def _get_logger():
    """Lazy logger creation to avoid import overhead at module load."""
    from terminaluse.lib.utils.logging import make_logger

    return make_logger(__name__)


def _format_status(status: str | None) -> str:
    """Format namespace status with color."""
    if status is None:
        return "[dim]unknown[/dim]"
    status_lower = status.lower()
    if status_lower == "ready":
        return "[green]ready[/green]"
    elif status_lower == "pending":
        return "[yellow]pending[/yellow]"
    elif status_lower == "failed":
        return "[red]failed[/red]"
    return status


@namespaces.command("ls")
def ls(
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
):
    """List all namespaces you have access to."""
    import json

    from terminaluse.lib.cli.utils.client import get_authenticated_client

    logger = _get_logger()

    try:
        client = get_authenticated_client()
        namespace_list = list(client.namespaces.list())

        if json_output:
            output = [
                {
                    "id": ns.id,
                    "slug": ns.slug,
                    "name": ns.name,
                    "status": ns.status if ns.status else None,
                    "created_at": ns.created_at.isoformat() if ns.created_at else None,
                }
                for ns in namespace_list
            ]
            typer.echo(json.dumps(output, default=str))
            return

        if not namespace_list:
            console.print("[dim]No namespaces found.[/dim]")
            console.print()
            console.print("Create a namespace at [cyan]https://terminaluse.com[/cyan]")
            return

        # Create table
        table = Table(show_header=True, header_style="bold")
        table.add_column("Slug", style="cyan")
        table.add_column("Name")
        table.add_column("Status")
        table.add_column("Created", style="dim")

        for ns in namespace_list:
            created = ns.created_at.strftime("%Y-%m-%d") if ns.created_at else "-"
            status = _format_status(ns.status if ns.status else None)
            table.add_row(ns.slug, ns.name, status, created)

        console.print(table)

    except CLIError:
        raise
    except ApiError:
        raise
    except Exception as e:
        logger.debug("Namespace list failed", exc_info=True)
        raise CLIError.from_unexpected(e)


# Add 'list' as a hidden alias for 'ls'
namespaces.command("list", hidden=True)(ls)
