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

costs_app = typer.Typer(help="Resumos de custos por safra.")


def _post_summary(path: str, crop_key: str, output: OutputFormat, empty_msg: str) -> None:
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {"cropKey": crop_key}
        result = client.post(path, api_key=api_key, json_body=body)
        if result is None:
            typer.echo(empty_msg)
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@costs_app.command("by-asset")
def summary_by_asset(
    crop_key: str = typer.Option(..., "--crop-key", help="Chave da safra."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Resumo de custos agrupado por patrimonio (asset) na safra.

    EXAMPLES:
      aegro costs by-asset --crop-key crop::abc
    """
    _post_summary(
        "/pub/v1/costs/summary/by-asset/filter",
        crop_key,
        output,
        "Nenhum custo encontrado.",
    )


@costs_app.command("by-element")
def summary_by_element(
    crop_key: str = typer.Option(..., "--crop-key", help="Chave da safra."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Resumo de custos agrupado por produtos e servicos (elemento) na safra.

    EXAMPLES:
      aegro costs by-element --crop-key crop::abc
    """
    _post_summary(
        "/pub/v1/costs/summary/by-element/filter",
        crop_key,
        output,
        "Nenhum custo encontrado.",
    )


@costs_app.command("by-category")
def summary_by_category(
    crop_key: str = typer.Option(..., "--crop-key", help="Chave da safra."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Resumo de custos agrupado por categoria financeira na safra.

    EXAMPLES:
      aegro costs by-category --crop-key crop::abc
    """
    _post_summary(
        "/pub/v1/costs/summary/by-financial-category/filter",
        crop_key,
        output,
        "Nenhum custo encontrado.",
    )
