from __future__ import annotations

from typing import Optional

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

crops_app = typer.Typer(help="Safras e ciclos produtivos.")


@crops_app.command("get")
def get_crop(
    crop_key: str = typer.Argument(help="Chave unica da safra."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Retorna os dados de uma safra pelo seu identificador.

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


@crops_app.command("list")
def list_crops(
    start_date: Optional[str] = typer.Option(
        None, "--start-date", help="Data inicial (YYYY-MM-DD)."
    ),
    end_date: Optional[str] = typer.Option(None, "--end-date", help="Data final (YYYY-MM-DD)."),
    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 safras da fazenda ativa com filtros opcionais.

    EXAMPLES:
      aegro crops list
      aegro crops list --start-date 2025-01-01 --end-date 2025-12-31
      aegro crops list --page 2 --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if start_date is not None:
            body["startDate"] = start_date
        if end_date is not None:
            body["endDate"] = end_date
        result = client.post("/pub/v1/crops/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhuma safra encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@crops_app.command("prorate")
def get_crop_prorate(
    prorate_key: str = typer.Argument(help="Chave unica do grupo de rateio."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Retorna os dados de um grupo de rateio de safra.

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


@crops_app.command("harvest-discounts")
def list_crop_harvest_discounts(
    crop_key: str = typer.Argument(help="Chave unica da safra."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Lista os descontos de colheita de uma safra.

    EXAMPLES:
      aegro crops harvest-discounts abc123
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get(
            f"/pub/v1/crops/{validate_key(crop_key)}/crop-harvest-log-discounts",
            api_key=api_key,
        )
        if result is None:
            typer.echo("Nenhum desconto de colheita encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@crops_app.command("prorates")
def list_crop_prorates(
    crop_key: Optional[list[str]] = typer.Option(
        None, "--crop-key", help="Chave de safra (repetivel para multiplas)."
    ),
    status: Optional[list[str]] = typer.Option(
        None, "--status", help="Status: ACTIVE, ARCHIVED (repetivel)."
    ),
    search: Optional[str] = typer.Option(None, "--search", help="Texto de busca."),
    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 grupos de rateio de safra com filtros.

    EXAMPLES:
      aegro crops prorates
      aegro crops prorates --crop-key abc --crop-key def --status ACTIVE
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if crop_key:
            body["cropKeys"] = crop_key
        if status:
            body["statuses"] = status
        if search is not None:
            body["searchText"] = search
        result = client.post("/pub/v1/crop-prorate/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhum grupo de rateio encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@crops_app.command("glebes")
def list_crop_glebes_by_crop(
    crop_key: str = typer.Argument(help="Chave unica da safra."),
    glebe_key: Optional[list[str]] = typer.Option(
        None, "--glebe-key", help="Chave de talhao (repetivel)."
    ),
    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 crops glebes abc123
      aegro crops glebes abc123 --glebe-key g1 --glebe-key g2
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if glebe_key:
            body["cropGlebeKeys"] = glebe_key
        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)
