"""Volumes CLI commands."""

from __future__ import annotations

import typer

volumes_app = typer.Typer(help="Manage volumes")


@volumes_app.command("list")
def volumes_list(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    app_id: int = typer.Option(..., "--app", "-a", help="App ID"),
    output: str = typer.Option("table", "--output", "-o", help="Output format"),
) -> None:
    """List volumes for an app."""
    from appliku.cli import get_client, render_output

    client = get_client()
    result = client.volumes.list(team, app_id)
    rows = [
        {"id": v.id, "name": v.name, "container_path": v.container_path, "url": v.url}
        for v in result.results
    ]
    render_output(rows, ["id", "name", "container_path", "url"], output, title="Volumes")


@volumes_app.command("create")
def volumes_create(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    app_id: int = typer.Option(..., "--app", "-a", help="App ID"),
    name: str = typer.Option(..., "--name", "-n", help="Volume name"),
    container_path: str = typer.Option(..., "--path", "-p", help="Container mount path"),
    env_var: str | None = typer.Option(None, "--env-var", help="Environment variable name"),
) -> None:
    """Create a volume."""
    from appliku.cli import get_client

    client = get_client()
    kwargs: dict[str, object] = {}
    if env_var:
        kwargs["environment_variable"] = env_var
    v = client.volumes.create(team, app_id, name, container_path, **kwargs)
    typer.echo(f"Created volume '{v.name}' (ID: {v.id})")


@volumes_app.command("update")
def volumes_update(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    app_id: int = typer.Option(..., "--app", "-a", help="App ID"),
    vol_id: int = typer.Argument(..., help="Volume ID"),
    name: str | None = typer.Option(None, "--name", "-n"),
    container_path: str | None = typer.Option(None, "--path", "-p"),
    env_var: str | None = typer.Option(None, "--env-var"),
) -> None:
    """Update a volume."""
    from appliku.cli import get_client

    client = get_client()
    kwargs: dict[str, object] = {}
    if name is not None:
        kwargs["name"] = name
    if container_path is not None:
        kwargs["container_path"] = container_path
    if env_var is not None:
        kwargs["environment_variable"] = env_var
    v = client.volumes.update(team, app_id, vol_id, **kwargs)
    typer.echo(f"Updated volume '{v.name}'")


@volumes_app.command("delete")
def volumes_delete(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    app_id: int = typer.Option(..., "--app", "-a", help="App ID"),
    vol_id: int = typer.Argument(..., help="Volume ID"),
) -> None:
    """Delete a volume."""
    from appliku.cli import get_client

    client = get_client()
    client.volumes.delete(team, app_id, vol_id)
    typer.echo(f"Deleted volume {vol_id}")
