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

crop_glebes_app = typer.Typer(help="Talhoes de safra (crop-glebes).")


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

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


@crop_glebes_app.command("list")
def list_crop_glebes(
    crop_key: str = typer.Argument(help="Chave unica da safra."),
    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 de uma safra especifica.

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