from __future__ import annotations

from pathlib import Path
from typing import Optional

import typer

from aegro.cli._config import get_client, require_farm
from aegro.cli._errors import handle_error
from aegro.validation import validate_key

mdfes_app = typer.Typer(help="Downloads de XML de MDF-e.")


@mdfes_app.command("xml")
def download_mdfe_xml(
    key: str = typer.Argument(help="Chave unica do MDF-e."),
    output_path: Path = typer.Option(
        ..., "--output-path", "-o", help="Caminho do arquivo XML de destino."
    ),
) -> None:
    """Baixa o XML de um MDF-e pela chave do documento.

    EXAMPLES:
      aegro mdfes xml mdfe::abc -o ./mdfe.xml
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        data = client.download(f"/pub/v1/mdfes/{validate_key(key)}/xml", api_key=api_key)
        if not data:
            typer.echo("MDF-e nao encontrado.")
            return
        output_path.write_bytes(data)
        typer.echo(f"XML salvo em {output_path} ({len(data)} bytes).")
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@mdfes_app.command("xml-batch")
def download_mdfe_xml_batch(
    output_path: Path = typer.Option(
        ..., "--output-path", "-o", help="Caminho do arquivo ZIP de destino."
    ),
    search_text: Optional[str] = typer.Option(None, "--search-text", help="Texto de busca."),
    series: Optional[list[str]] = typer.Option(None, "--series", help="Serie (repetivel)."),
    number: Optional[list[str]] = typer.Option(None, "--number", help="Numero (repetivel)."),
    access_key: Optional[list[str]] = typer.Option(
        None, "--access-key", help="Chave de acesso (repetivel)."
    ),
    issuer_key: Optional[list[str]] = typer.Option(
        None, "--issuer-key", help="Chave de emissor (repetivel)."
    ),
    nfe_key: Optional[list[str]] = typer.Option(
        None, "--nfe-key", help="Chave de NF-e vinculada (repetivel)."
    ),
    status: Optional[list[str]] = typer.Option(None, "--status", help="Status (repetivel)."),
    traction_vehicle_key: Optional[list[str]] = typer.Option(
        None, "--traction-vehicle-key", help="Chave de veiculo de tracao (repetivel)."
    ),
    driver_key: Optional[list[str]] = typer.Option(
        None, "--driver-key", help="Chave de motorista (repetivel)."
    ),
    issued_start_date: Optional[str] = typer.Option(
        None, "--issued-start-date", help="Data de emissao inicial (YYYY-MM-DD)."
    ),
    issued_end_date: Optional[str] = typer.Option(
        None, "--issued-end-date", help="Data de emissao final (YYYY-MM-DD)."
    ),
    trip_start_start_date: Optional[str] = typer.Option(
        None, "--trip-start-start-date", help="Data de inicio de viagem inicial (YYYY-MM-DD)."
    ),
    trip_start_end_date: Optional[str] = typer.Option(
        None, "--trip-start-end-date", help="Data de inicio de viagem final (YYYY-MM-DD)."
    ),
    page: int = typer.Option(1, "--page", help="Numero da pagina."),
) -> None:
    """Baixa um ZIP com XMLs de MDF-es filtrados.

    EXAMPLES:
      aegro mdfes xml-batch -o ./mdfes.zip --issued-start-date 2025-01-01 --issued-end-date 2025-12-31
      aegro mdfes xml-batch -o ./saida.zip --status AUTHORIZED
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if search_text is not None:
            body["searchText"] = search_text
        if series:
            body["series"] = series
        if number:
            body["numbers"] = number
        if access_key:
            body["accessKeys"] = access_key
        if issuer_key:
            body["issuerKeys"] = issuer_key
        if nfe_key:
            body["nfeKeys"] = nfe_key
        if status:
            body["status"] = status
        if traction_vehicle_key:
            body["tractionVehicleKeys"] = traction_vehicle_key
        if driver_key:
            body["driverKeys"] = driver_key
        if issued_start_date is not None:
            body["issuedStartDate"] = issued_start_date
        if issued_end_date is not None:
            body["issuedEndDate"] = issued_end_date
        if trip_start_start_date is not None:
            body["tripStartStartDate"] = trip_start_start_date
        if trip_start_end_date is not None:
            body["tripStartEndDate"] = trip_start_end_date
        data = client.download(
            "/pub/v1/mdfes/xmls/filter",
            api_key=api_key,
            method="POST",
            json_body=body,
        )
        if not data:
            typer.echo("Nenhum MDF-e encontrado para o filtro informado.")
            return
        output_path.write_bytes(data)
        typer.echo(f"ZIP salvo em {output_path} ({len(data)} bytes).")
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
