"""Deployments CLI commands."""

from __future__ import annotations

import typer

deployments_app = typer.Typer(help="Manage deployments")


@deployments_app.command("list")
def deployments_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 deployments for an app."""
    from appliku.cli import get_client, render_output

    client = get_client()
    result = client.deployments.list(team, app_id)
    rows = [
        {
            "id": d.id,
            "status": d.status,
            "branch": d.branch,
            "git_commit": d.git_commit,
            "is_active": d.is_active,
        }
        for d in result.results
    ]
    render_output(
        rows, ["id", "status", "branch", "git_commit", "is_active"], output, title="Deployments"
    )


@deployments_app.command("latest")
def deployments_latest(
    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:
    """Get the latest deployment for an app."""
    from appliku.cli import get_client, render_output

    client = get_client()
    d = client.deployments.latest(team, app_id)
    rows = [
        {
            "id": d.id,
            "status": d.status,
            "branch": d.branch,
            "git_commit": d.git_commit,
            "is_active": d.is_active,
        }
    ]
    render_output(
        rows,
        ["id", "status", "branch", "git_commit", "is_active"],
        output,
        title="Latest Deployment",
    )


@deployments_app.command("logs")
def deployments_logs(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    app_id: int = typer.Option(..., "--app", "-a", help="App ID"),
    deployment_id: int = typer.Option(..., "--deployment", "-d", help="Deployment ID"),
    stream: bool = typer.Option(False, "--stream", "-s", help="Stream logs in real-time"),
) -> None:
    """Get deployment logs."""
    from appliku.cli import get_client

    client = get_client()

    if stream:
        typer.echo("Streaming logs (Ctrl+C to stop)...")
        for entry in client.deployments.stream_logs(team, app_id, deployment_id):
            typer.echo(f"[{entry.timestamp or ''}] {entry.message}")
    else:
        entries = client.deployments.logs(team, app_id, deployment_id)
        for entry in entries:
            typer.echo(f"[{entry.timestamp or ''}] {entry.message}")
