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

catalogs_app = typer.Typer(help="Catalogos e elementos.")


@catalogs_app.command("list")
def list_catalogs(
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Lista todos os catalogos disponiveis.

    EXAMPLES:
      aegro catalogs list
      aegro catalogs list --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get("/pub/v1/catalogs", api_key=api_key)
        if result is None:
            typer.echo("Nenhum catalogo encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@catalogs_app.command("element-keys")
def list_element_keys(
    catalog_key: str = typer.Argument(help="Chave unica do catalogo."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Lista as chaves dos elementos de um catalogo.

    EXAMPLES:
      aegro catalogs element-keys cat-1
      aegro catalogs element-keys cat-1 --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get(
            f"/pub/v1/catalogs/{validate_key(catalog_key)}/elements/keys",
            api_key=api_key,
        )
        if result is None:
            typer.echo("Nenhuma chave de elemento encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@catalogs_app.command("elements")
def list_elements(
    catalog_key: str = typer.Argument(help="Chave unica do catalogo."),
    category: Optional[list[str]] = typer.Option(
        None, "--category", help="Categoria de elemento (repetivel)."
    ),
    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 elementos de um catalogo com filtros opcionais.

    EXAMPLES:
      aegro catalogs elements cat-1
      aegro catalogs elements cat-1 --category SEED --category FERTILIZER
      aegro catalogs elements cat-1 --search-text "Ureia" --page 2
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if category:
            body["categories"] = category
        if search_text is not None:
            body["searchText"] = search_text
        result = client.post(
            f"/pub/v1/catalogs/{validate_key(catalog_key)}/elements/filter",
            api_key=api_key,
            json_body=body,
        )
        if result is None:
            typer.echo("Nenhum elemento encontrado.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
