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

harvest_logs_app = typer.Typer(help="Registros de colheita.")


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

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


@harvest_logs_app.command("create")
def create_harvest_log(
    crop_key: str = typer.Option(..., "--crop-key", help="Chave da safra."),
    date: str = typer.Option(..., "--date", help="Data da colheita (YYYY-MM-DD)."),
    crop_glebe: Optional[list[str]] = typer.Option(
        None,
        "--crop-glebe",
        help="Chave de talhao de safra (repetivel para multiplos).",
    ),
    calculation_mode: str = typer.Option(
        "AUTOMATIC",
        "--calculation-mode",
        help="Modo de calculo: AUTOMATIC|MANUAL (default: AUTOMATIC).",
    ),
    seed_key: Optional[str] = typer.Option(None, "--seed-key", help="Chave da semente."),
    destination_key: Optional[str] = typer.Option(
        None, "--destination-key", help="Chave do destino."
    ),
    gross_weight: Optional[float] = typer.Option(None, "--gross-weight", help="Peso bruto em kg."),
    tare_weight: Optional[float] = typer.Option(None, "--tare-weight", help="Peso da tara em kg."),
    net_weight: Optional[float] = typer.Option(None, "--net-weight", help="Peso liquido em kg."),
    discounted_weight: Optional[float] = typer.Option(
        None, "--discounted-weight", help="Peso descontado em kg."
    ),
    product_weight: Optional[float] = typer.Option(
        None, "--product-weight", help="Peso do produto em kg."
    ),
    observations: Optional[str] = typer.Option(
        None, "--observations", help="Observacoes opcionais."
    ),
    identifier: Optional[str] = typer.Option(
        None, "--identifier", help="Identificador do registro."
    ),
    invoice_code: Optional[str] = typer.Option(
        None, "--invoice-code", help="Codigo da nota fiscal."
    ),
    romaneio_code: Optional[str] = typer.Option(
        None, "--romaneio-code", help="Codigo do romaneio."
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Cria um novo registro de colheita.

    EXAMPLES:
      aegro harvest-logs create --crop-key c1 --date 2025-06-01
      aegro harvest-logs create --crop-key c1 --date 2025-06-01 --crop-glebe g1 --crop-glebe g2 --gross-weight 1000
    """
    try:
        farm_name, api_key = require_farm()
        client = get_client()
        body: dict = {
            "cropKey": crop_key,
            "date": date,
            "calculationMode": calculation_mode,
        }
        if crop_glebe:
            body["cropGlebes"] = [{"cropGlebeKey": k} for k in crop_glebe]
        if seed_key is not None:
            body["seedKey"] = seed_key
        if destination_key is not None:
            body["destinationKey"] = destination_key
        if gross_weight is not None:
            body["grossWeight"] = {"magnitude": gross_weight, "unit": "kg"}
        if tare_weight is not None:
            body["tareWeight"] = {"magnitude": tare_weight, "unit": "kg"}
        if net_weight is not None:
            body["netWeight"] = {"magnitude": net_weight, "unit": "kg"}
        if discounted_weight is not None:
            body["discountedWeight"] = {"magnitude": discounted_weight, "unit": "kg"}
        if product_weight is not None:
            body["productWeight"] = {"magnitude": product_weight, "unit": "kg"}
        if observations is not None:
            body["observations"] = observations
        if identifier is not None:
            body["identifier"] = identifier
        if invoice_code is not None:
            body["invoiceCode"] = invoice_code
        if romaneio_code is not None:
            body["romaneioCode"] = romaneio_code
        result = client.post("/pub/v1/harvest-logs", api_key=api_key, json_body=body)
        if result is None:
            typer.echo(f"Registro de colheita criado na fazenda '{farm_name}'.")
        else:
            typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
