from __future__ import annotations

import typer

from aegro.cli._config import (
    get_client,
    get_selected_farm,
    get_settings,
    set_selected_farm,
)
from aegro.cli._errors import handle_error
from aegro.cli._output import OutputFormat, format_output

farms_app = typer.Typer(help="Gerenciar fazendas.")


@farms_app.command("list")
def list_farms(
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Lista todas as fazendas disponiveis.

    EXAMPLES:
      aegro farms list
      aegro farms list --output table
    """
    settings = get_settings()
    current = get_selected_farm()
    farms = [{"name": name, "active": name == current} for name in settings.farm_names()]
    typer.echo(format_output(farms, output))


@farms_app.command("select")
def select_farm(
    farm_name: str = typer.Argument(help="Nome exato da fazenda."),
) -> None:
    """Seleciona a fazenda ativa para operacoes subsequentes.

    EXAMPLES:
      aegro farms select "Fazenda Sul"
    """
    settings = get_settings()
    if farm_name not in settings.farms:
        names = ", ".join(settings.farm_names())
        typer.echo(
            f"Fazenda '{farm_name}' nao encontrada. Disponiveis: {names}",
            err=True,
        )
        raise typer.Exit(1)
    set_selected_farm(farm_name)
    typer.echo(f"Fazenda ativa: {farm_name}")


@farms_app.command("info")
def farm_info(
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Mostra informacoes da fazenda ativa via API.

    EXAMPLES:
      aegro farms info
      aegro farms info --output table
    """
    try:
        from aegro.cli._config import require_farm

        _, api_key = require_farm()
        client = get_client()
        result = client.get("/pub/v1/farms", api_key=api_key)
        if result is None:
            typer.echo("Nenhum dado retornado para esta fazenda.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
