from __future__ import annotations

import typer

from aegro.cli._config import get_client, require_farm
from aegro.cli._errors import handle_error
from aegro.cli._output import OutputFormat, format_output
from aegro.validation import validate_key

glebes_app = typer.Typer(help="Talhoes (glebas) da fazenda.")


@glebes_app.command("get")
def get_glebe(
    key: str = typer.Argument(help="Chave unica do talhao."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Retorna os dados de um talhao pelo seu identificador.

    EXAMPLES:
      aegro glebes get abc123
      aegro glebes get abc123 --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get(f"/pub/v1/glebes/{validate_key(key)}", api_key=api_key)
        if result is None:
            typer.echo("Talhao nao encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@glebes_app.command("list")
def list_glebes(
    page: int = typer.Option(1, "--page", help="Numero da pagina."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Lista talhoes da fazenda ativa.

    EXAMPLES:
      aegro glebes list
      aegro glebes list --page 2 --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        result = client.post("/pub/v1/glebes/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhum talhao encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
