"""Teams CLI commands."""

from __future__ import annotations

import typer

teams_app = typer.Typer(help="Manage teams")


@teams_app.command("list")
def teams_list(
    output: str = typer.Option("table", "--output", "-o", help="Output format: table or json"),
) -> None:
    """List all teams."""
    from appliku.cli import get_client, render_output

    client = get_client()
    teams = client.teams.list()
    rows = [
        {"id": t.id, "team_path": t.team_path, "name": t.name, "plan": t.plan}
        for t in teams
    ]
    render_output(rows, ["id", "team_path", "name", "plan"], output, title="Teams")


@teams_app.command("get")
def teams_get(
    team: str = typer.Argument(..., help="Team path"),
    output: str = typer.Option("table", "--output", "-o", help="Output format"),
) -> None:
    """Get details of a team."""
    from appliku.cli import get_client, render_output

    client = get_client()
    t = client.teams.get(team)
    rows = [{"id": t.id, "team_path": t.team_path, "name": t.name, "plan": t.plan}]
    render_output(rows, ["id", "team_path", "name", "plan"], output, title=f"Team: {team}")


@teams_app.command("create")
def teams_create(
    team_path: str = typer.Option(..., "--path", "-p", help="Team path slug"),
    name: str = typer.Option(..., "--name", "-n", help="Team name"),
) -> None:
    """Create a new team."""
    from appliku.cli import get_client

    client = get_client()
    team = client.teams.create(team_path, name)
    typer.echo(f"Created team '{team.name}' (path: {team.team_path})")


@teams_app.command("update")
def teams_update(
    team: str = typer.Argument(..., help="Team path"),
    name: str | None = typer.Option(None, "--name", "-n", help="New name"),
) -> None:
    """Update a team."""
    from appliku.cli import get_client

    client = get_client()
    kwargs: dict[str, object] = {}
    if name is not None:
        kwargs["name"] = name
    updated = client.teams.update(team, **kwargs)
    typer.echo(f"Updated team '{updated.name}'")


@teams_app.command("delete")
def teams_delete(
    team: str = typer.Argument(..., help="Team path"),
) -> None:
    """Delete a team."""
    from appliku.cli import get_client

    client = get_client()
    client.teams.delete(team)
    typer.echo(f"Deleted team '{team}'")
