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

cash_flow_app = typer.Typer(help="Fluxo de caixa.")


@cash_flow_app.command("list")
def list_cash_flow(
    start_date: str = typer.Option(..., "--start-date", help="Data inicial (YYYY-MM-DD)."),
    end_date: str = typer.Option(..., "--end-date", help="Data final (YYYY-MM-DD)."),
    bank_account_key: Optional[list[str]] = typer.Option(
        None, "--bank-account-key", help="Chave de conta bancaria (repetivel)."
    ),
    company_key: Optional[list[str]] = typer.Option(
        None, "--company-key", help="Chave de empresa (repetivel)."
    ),
    crop_key: Optional[list[str]] = typer.Option(
        None, "--crop-key", help="Chave de safra (repetivel)."
    ),
    financial_category_key: Optional[list[str]] = typer.Option(
        None, "--financial-category-key", help="Chave de categoria financeira (repetivel)."
    ),
    all_tags: Optional[list[str]] = typer.Option(
        None, "--all-tag", help="Tag que deve estar presente (operador AND, repetivel)."
    ),
    any_tags: Optional[list[str]] = typer.Option(
        None, "--any-tag", help="Tag alternativa (operador OR, repetivel)."
    ),
    structure_type: Optional[str] = typer.Option(
        None,
        "--structure-type",
        help=(
            "Tipo: ANALYTIC_FINANCIAL_CATEGORY|SYNTHETIC_FINANCIAL_CATEGORY|"
            "SECOND_LEVEL_FINANCIAL_CATEGORY|THIRD_LEVEL_FINANCIAL_CATEGORY."
        ),
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Consulta o fluxo de caixa no periodo informado.

    EXAMPLES:
      aegro cash-flow list --start-date 2025-01-01 --end-date 2025-12-31
      aegro cash-flow list --start-date 2025-01-01 --end-date 2025-06-30 --crop-key c1
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {"startDate": start_date, "endDate": end_date}
        if bank_account_key:
            body["bankAccountKeys"] = bank_account_key
        if company_key:
            body["companyKeys"] = company_key
        if crop_key:
            body["cropKeys"] = crop_key
        if financial_category_key:
            body["financialCategoryKeys"] = financial_category_key
        if all_tags:
            body["allTags"] = all_tags
        if any_tags:
            body["anyTags"] = any_tags
        if structure_type is not None:
            body["structureType"] = structure_type
        result = client.post("/pub/v1/cash-flow/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhum resultado de fluxo de caixa.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
