"""Clusters CLI commands."""

from __future__ import annotations

import typer

clusters_app = typer.Typer(help="Manage clusters")


@clusters_app.command("list")
def clusters_list(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    output: str = typer.Option("table", "--output", "-o", help="Output format"),
) -> None:
    """List clusters for a team."""
    from appliku.cli import get_client, render_output

    client = get_client()
    clusters = client.clusters.list(team)
    rows = [
        {"id": c.id, "name": c.name, "apps_count": c.apps_count, "domains_count": c.domains_count}
        for c in clusters
    ]
    render_output(rows, ["id", "name", "apps_count", "domains_count"], output, title="Clusters")


@clusters_app.command("create")
def clusters_create(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    name: str = typer.Option(..., "--name", "-n", help="Cluster name"),
) -> None:
    """Create a cluster."""
    from appliku.cli import get_client

    client = get_client()
    cluster = client.clusters.create(team, name)
    typer.echo(f"Created cluster '{cluster.name}' (ID: {cluster.id})")


@clusters_app.command("delete")
def clusters_delete(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    cluster_id: int = typer.Argument(..., help="Cluster ID"),
) -> None:
    """Delete a cluster."""
    from appliku.cli import get_client

    client = get_client()
    client.clusters.delete(team, cluster_id)
    typer.echo(f"Deleted cluster {cluster_id}")


@clusters_app.command("logs")
def clusters_logs(
    team: str = typer.Option(..., "--team", "-t", help="Team path"),
    cluster_id: int = typer.Argument(..., help="Cluster ID"),
    process: str = typer.Option(..., "--process", "-p", help="Process/service name"),
    tail: int = typer.Option(100, "--tail", help="Number of log lines"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table or json"),
) -> None:
    """View service logs for all apps in a cluster."""
    import json

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

    from appliku.cli import get_client

    client = get_client()
    with Console().status(f"Fetching logs for process '{process}' across cluster {cluster_id}..."):
        entries = client.clusters.service_logs(team, cluster_id, process, tail)

    if not entries:
        typer.echo("No apps found in this cluster.")
        return

    if output == "json":
        rows = [
            {"app_name": app.name, "app_id": app.id, "logs": logs.logs} for app, logs in entries
        ]
        typer.echo(json.dumps(rows, indent=2))
    else:
        console = Console()
        table = Table(title=f"Cluster {cluster_id} — '{process}' logs")
        table.add_column("App")
        table.add_column("Logs")
        for app, logs in entries:
            table.add_row(app.name, logs.logs[:200] if len(logs.logs) > 200 else logs.logs)
        console.print(table)
