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

bank_movements_app = typer.Typer(help="Movimentacoes bancarias.")


@bank_movements_app.command("list")
def list_bank_movements(
    bank_account_key: Optional[list[str]] = typer.Option(
        None, "--bank-account-key", help="Chave da conta bancaria (repetivel)."
    ),
    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)."),
    financial_flow_type: Optional[list[str]] = typer.Option(
        None, "--financial-flow-type", help="Tipo de fluxo: INFLOW ou OUTFLOW (repetivel)."
    ),
    reconciliation_status: Optional[list[str]] = typer.Option(
        None, "--reconciliation-status", help="Status de conciliacao (repetivel)."
    ),
    installment_key: Optional[list[str]] = typer.Option(
        None, "--installment-key", help="Chave de parcela relacionada (repetivel)."
    ),
    bank_transfer_key: Optional[list[str]] = typer.Option(
        None, "--bank-transfer-key", help="Chave de transferencia relacionada (repetivel)."
    ),
    min_amount: Optional[float] = typer.Option(None, "--min-amount", help="Valor minimo."),
    max_amount: Optional[float] = typer.Option(None, "--max-amount", help="Valor maximo."),
    currency: str = typer.Option(
        "BRL", "--currency", help="Moeda para min/max-amount (default: BRL)."
    ),
    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 movimentacoes bancarias com filtros opcionais.

    EXAMPLES:
      aegro bank-movements list --start-date 2025-01-01 --end-date 2025-12-31
      aegro bank-movements list --financial-flow-type OUTFLOW --reconciliation-status CONFIRMED
      aegro bank-movements list --bank-account-key ba1 --min-amount 100.00
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if bank_account_key:
            body["bankAccountKeys"] = bank_account_key
        if start_date is not None:
            body["startDate"] = start_date
        if end_date is not None:
            body["endDate"] = end_date
        if financial_flow_type:
            body["financialFlowTypes"] = financial_flow_type
        if reconciliation_status:
            body["reconciliationStatuses"] = reconciliation_status
        if installment_key:
            body["installmentKeys"] = installment_key
        if bank_transfer_key:
            body["bankTransferKeys"] = bank_transfer_key
        if min_amount is not None:
            body["minAmount"] = {"amount": min_amount, "currency": currency}
        if max_amount is not None:
            body["maxAmount"] = {"amount": max_amount, "currency": currency}
        result = client.post(
            "/pub/v1/bank-account-movements/filter", api_key=api_key, json_body=body
        )
        if result is None:
            typer.echo("Nenhuma movimentacao encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
