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

fiscal_products_app = typer.Typer(help="Produtos fiscais (NF-e).")


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

    EXAMPLES:
      aegro fiscal-products get fiscalProduct::abc
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get(f"/pub/v1/fiscal-products/{validate_key(key)}", api_key=api_key)
        if result is None:
            typer.echo("Produto fiscal nao encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@fiscal_products_app.command("list")
def list_fiscal_products(
    search_text: Optional[str] = typer.Option(None, "--search-text", help="Texto de busca."),
    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 produtos fiscais da fazenda.

    EXAMPLES:
      aegro fiscal-products list
      aegro fiscal-products list --search-text "soja"
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if search_text is not None:
            body["searchText"] = search_text
        result = client.post("/pub/v1/fiscal-products/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhum produto fiscal encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@fiscal_products_app.command("create")
def create_fiscal_product(
    name: str = typer.Option(..., "--name", help="Nome do produto fiscal."),
    code: str = typer.Option(..., "--code", help="Codigo do produto."),
    description: str = typer.Option(..., "--description", help="Descricao detalhada."),
    ncm_code: str = typer.Option(..., "--ncm-code", help="Codigo NCM (8 digitos)."),
    measuring_unit: str = typer.Option(
        ..., "--measuring-unit", help="Unidade de medida (kg, t, L, sc 60kg, un, m3, ha)."
    ),
    cest_code: Optional[str] = typer.Option(None, "--cest-code", help="Codigo CEST."),
    gtin_code: Optional[str] = typer.Option(None, "--gtin-code", help="Codigo GTIN (EAN)."),
    additional_information: Optional[str] = typer.Option(
        None, "--additional-information", help="Informacoes adicionais para a NF-e."
    ),
    cbenef_code: Optional[str] = typer.Option(
        None, "--cbenef-code", help="Codigo de beneficio fiscal (CBENEF)."
    ),
    taxable_measuring_unit: Optional[str] = typer.Option(
        None, "--taxable-measuring-unit", help="Unidade de medida tributavel."
    ),
    global_fiscal_product_key: Optional[str] = typer.Option(
        None, "--global-fiscal-product-key", help="Chave do produto fiscal global de origem."
    ),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Cria um novo produto fiscal.

    EXAMPLES:
      aegro fiscal-products create --name "Soja" --code SOJA-001 --description "Soja em graos" \\
        --ncm-code 1201.90.00 --measuring-unit "sc 60kg"
    """
    try:
        farm_name, api_key = require_farm()
        client = get_client()
        body: dict = {
            "name": name,
            "code": code,
            "description": description,
            "ncmCode": ncm_code,
            "measuringUnit": measuring_unit,
            "global": False,
        }
        if cest_code is not None:
            body["cestCode"] = cest_code
        if gtin_code is not None:
            body["gtinCode"] = gtin_code
        if additional_information is not None:
            body["additionalInformation"] = additional_information
        if cbenef_code is not None:
            body["cbenefCode"] = cbenef_code
        if taxable_measuring_unit is not None:
            body["taxableMeasuringUnit"] = taxable_measuring_unit
        if global_fiscal_product_key is not None:
            body["globalFiscalProductKey"] = global_fiscal_product_key
        result = client.post("/pub/v1/fiscal-products", api_key=api_key, json_body=body)
        if result is None:
            typer.echo(f"Produto fiscal criado na {farm_name}.")
        else:
            typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
