# apps/aroflo_connector_app/zones/clients/cli.py
from __future__ import annotations

import json
from typing import Any

import click


def _echo(result: Any) -> None:
    if isinstance(result, (dict, list)):
        click.echo(json.dumps(result, indent=2, ensure_ascii=False))
    else:
        click.echo(str(result))


def register_cli(root: click.Group, zone: Any) -> None:
    """
    Estándar (igual invoices):
    - recibe root y la instancia de zona
    - NO crea client, NO toca env, NO toca registry
    """

    @root.group(name=zone.code)
    def clients_group():
        """Operaciones de la zona clients."""

    # -------------------------
    # GET base
    # -------------------------
    @clients_group.command("list")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--where", default="", show_default=True, help="Cláusula WHERE estilo AroFlo (opcional).")
    @click.option("--page-size", default=50, type=int, show_default=True, help="Límite server-side (maxpageresults).")
    @click.option("--max-items", default=20, type=int, show_default=True, help="Recorte local (CLI/AI).")
    @click.option("--no-compact", is_flag=True, help="Desactiva compactación local (devuelve respuesta grande).")
    @click.option("--raw", is_flag=True, help="Devuelve respuesta cruda + meta debug.")
    def list_cmd(page: int, where: str, page_size: int, max_items: int, no_compact: bool, raw: bool):
        result = zone.execute(
            "list_clients",
            params={
                "page": page,
                "where": where,
                "page_size": page_size,
                "max_items": max_items,
                "compact": not no_compact,
                "raw": raw,
            },
        )
        _echo(result)

    @clients_group.command("get")
    @click.option("--clientid", required=True, help="ClientID codificado (AroFlo).")
    @click.option("--no-compact", is_flag=True, help="Desactiva compactación local.")
    @click.option("--raw", is_flag=True, help="Devuelve respuesta cruda + meta debug.")
    def get_cmd(clientid: str, no_compact: bool, raw: bool):
        result = zone.execute("get_client", params={"clientid": clientid, "compact": not no_compact, "raw": raw})
        _echo(result)

    # -------------------------
    # JOINs
    # -------------------------
    @clients_group.command("list")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--where", default="", show_default=False, help="WHERE AroFlo (opcional).")
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=20, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def list_cmd(page: int, where: str, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "page": page,
            "where": where or None,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("list_clients", params=params)
        _echo(result)


    @clients_group.command("contacts")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--where", default="", show_default=False, help="WHERE AroFlo (opcional).")
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=20, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def contacts_cmd(page: int, where: str, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "page": page,
            "where": where or None,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("get_clients_join_contacts", params=params)
        _echo(result)


    @clients_group.command("locations")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--where", default="", show_default=False, help="WHERE AroFlo (opcional).")
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=20, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def locations_cmd(page: int, where: str, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "page": page,
            "where": where or None,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("get_clients_join_locations", params=params)
        _echo(result)


    @clients_group.command("customfields")
    @click.option("--clientid", required=True)
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=5, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def customfields_cmd(clientid: str, page: int, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "clientid": clientid,
            "page": page,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("get_clients_join_customfields", params=params)
        _echo(result)

    @clients_group.command("locationcustomfields")
    @click.option("--clientid", required=True, help="ClientID codificado (AroFlo).")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=1, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def locationcustomfields_cmd(clientid: str, page: int, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "clientid": clientid,
            "page": page,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("get_clients_join_locationcustomfields", params=params)
        _echo(result)


    @clients_group.command("documentsandphotos")
    @click.option("--clientid", required=True, help="ClientID codificado (AroFlo).")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=5, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def documentsandphotos_cmd(clientid: str, page: int, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "clientid": clientid,
            "page": page,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("get_clients_join_documentsandphotos", params=params)
        _echo(result)


    @clients_group.command("priorities")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--where", default="", show_default=False, help="WHERE AroFlo (opcional).")
    @click.option("--page-size", default=0, type=int, show_default=True, help="maxpageresults (0 = no enviar).")
    @click.option("--compact/--no-compact", default=True, show_default=True)
    @click.option("--max-items", default=20, type=int, show_default=True)
    @click.option("--raw", is_flag=True)
    def priorities_cmd(page: int, where: str, page_size: int, compact: bool, max_items: int, raw: bool):
        params = {
            "page": page,
            "where": where or None,
            "page_size": (page_size if page_size > 0 else None),
            "compact": compact,
            "max_items": max_items,
            "raw": raw,
        }
        result = zone.execute("get_clients_join_priorities", params=params)
        _echo(result)



    # -------------------------
    # Sync incremental: postable
    # -------------------------
    @clients_group.command("postable")
    @click.option("--page", default=1, type=int, show_default=True)
    @click.option("--page-size", default=50, type=int, show_default=True, help="Límite server-side (maxpageresults).")
    @click.option("--max-items", default=20, type=int, show_default=True, help="Recorte local.")
    @click.option("--no-compact", is_flag=True, help="Desactiva compactación local.")
    @click.option("--raw", is_flag=True, help="Devuelve respuesta cruda + meta debug.")
    def postable_cmd(page: int, page_size: int, max_items: int, no_compact: bool, raw: bool):
        result = zone.execute(
            "get_postable_updated_clients",
            params={"page": page, "page_size": page_size, "max_items": max_items, "compact": not no_compact, "raw": raw},
        )
        _echo(result)

    @clients_group.command("reset-postable")
    @click.option("--clientids", required=True, help='JSON con ids. Ej: \'{"ids":["id1","id2"]}\'')
    @click.option("--raw", is_flag=True, help="Devuelve respuesta cruda + meta debug.")
    def reset_postable_cmd(clientids: str, raw: bool):
        obj = json.loads(clientids)
        result = zone.execute("reset_postable_flags", params={"client_ids": obj, "raw": raw})
        _echo(result)
