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

tags_app = typer.Typer(help="Tags e etiquetas.")


@tags_app.command("get")
def get_tag(
    key: str = typer.Argument(help="Chave unica da tag."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Retorna os dados de uma tag pelo seu identificador.

    EXAMPLES:
      aegro tags get abc123
      aegro tags get abc123 --output table
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        result = client.get(f"/pub/v1/tags/{validate_key(key)}", api_key=api_key)
        if result is None:
            typer.echo("Tag nao encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@tags_app.command("list")
def list_tags(
    relation_type: Optional[list[str]] = typer.Option(
        None, "--relation-type", help="Tipo de relacao (repetivel para multiplos)."
    ),
    status: Optional[list[str]] = typer.Option(
        None, "--status", help="Status (repetivel para multiplos)."
    ),
    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 tags com filtros opcionais.

    EXAMPLES:
      aegro tags list
      aegro tags list --relation-type CROP --relation-type ACTIVITY --status ACTIVE
      aegro tags list --search-text "soja" --page 2
    """
    try:
        _, api_key = require_farm()
        client = get_client()
        body: dict = {
            "requiredPageNumber": page,
            "maximumItemsPerPageCount": 50,
        }
        if relation_type:
            body["relationTypes"] = relation_type
        if status:
            body["statuses"] = status
        if search_text is not None:
            body["searchText"] = search_text
        result = client.post("/pub/v1/tags/filter", api_key=api_key, json_body=body)
        if result is None:
            typer.echo("Nenhuma tag encontrada.")
            return
        typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@tags_app.command("create")
def create_tag(
    name: str = typer.Option(..., "--name", help="Nome da tag."),
    relation_type: str = typer.Option(..., "--relation-type", help="Tipo de relacao."),
    status: Optional[str] = typer.Option(None, "--status", help="Status da tag."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Cria uma nova tag.

    EXAMPLES:
      aegro tags create --name "Organico" --relation-type CROP
      aegro tags create --name "Urgente" --relation-type ACTIVITY --status ACTIVE
    """
    try:
        farm_name, api_key = require_farm()
        client = get_client()
        body: dict = {
            "name": name,
            "relationType": relation_type,
        }
        if status is not None:
            body["status"] = status
        result = client.post("/pub/v1/tags", api_key=api_key, json_body=body)
        if result is None:
            typer.echo(f"Tag criada na {farm_name}.")
        else:
            typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)


@tags_app.command("update")
def update_tag(
    key: str = typer.Argument(help="Chave unica da tag."),
    name: str = typer.Option(..., "--name", help="Nome da tag."),
    relation_type: str = typer.Option(..., "--relation-type", help="Tipo de relacao."),
    status: Optional[str] = typer.Option(None, "--status", help="Status (ACTIVE ou ARCHIVED)."),
    output: OutputFormat = typer.Option(
        OutputFormat.json, "--output", "-o", help="Formato: json|table|csv"
    ),
) -> None:
    """Atualiza uma tag existente.

    EXAMPLES:
      aegro tags update tag::abc --name "Soja 2025" --relation-type CROP
      aegro tags update tag::abc --name "Arquivada" --relation-type ACTIVITY --status ARCHIVED
    """
    try:
        farm_name, api_key = require_farm()
        client = get_client()
        body: dict = {
            "name": name,
            "relationType": relation_type,
        }
        if status is not None:
            body["status"] = status
        result = client.put(f"/pub/v1/tags/{validate_key(key)}", api_key=api_key, json_body=body)
        if result is None:
            typer.echo(f"Tag atualizada na {farm_name}.")
        else:
            typer.echo(format_output(result, output))
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as exc:
        handle_error(exc)
