# apps/leave_form_app/api/v1/routes_trackingcentres.py
import os
import sys
import json
import subprocess
from pathlib import Path
from typing import Optional, List, Dict, Any

from flask import Blueprint, request, jsonify, current_app

trackingcentres_bp = Blueprint("leave_app_trackingcentres", __name__)

def _project_root() -> str:
    return str(Path(__file__).resolve().parents[4])  # /var/www/html/flask_server

def _run_cli(cmd: List[str]) -> Dict[str, Any]:
    project_root = _project_root()

    env = os.environ.copy()
    env["PYTHONPATH"] = project_root + (":" + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
    env["PYTHONNOUSERSITE"] = "1"

    current_app.logger.info("[leave_app] trackingcentres cmd=%s", " ".join(cmd))

    proc = subprocess.run(
        cmd,
        cwd=project_root,
        env=env,
        capture_output=True,
        text=True,
        check=False,
    )

    if proc.returncode != 0:
        raise RuntimeError(
            f"trackingcentres CLI failed rc={proc.returncode} "
            f"stderr={proc.stderr.strip()[:800]} stdout={proc.stdout.strip()[:800]}"
        )

    out = (proc.stdout or "").strip()
    if not out:
        raise RuntimeError("trackingcentres CLI returned empty stdout")

    return json.loads(out)

def _extract_items(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
    zr = payload.get("zoneresponse", {}) if isinstance(payload, dict) else {}
    items = zr.get("trackingcentres", []) if isinstance(zr, dict) else []
    return items if isinstance(items, list) else []

@trackingcentres_bp.get("/trackingcentres")
def trackingcentres_list():
    bu_name = (request.args.get("bu_name") or "").strip()
    pagesize = (request.args.get("pagesize") or "").strip()

    cmd = [
        sys.executable,
        "-m",
        "apps.aroflo_connector_app.cli",
        "trackingcentres",
        "list",
    ]

    if pagesize:
        cmd += ["--pagesize", pagesize]

    # Si en tu CLI soportas --order/--where, puedes pasarlos también:
    order = (request.args.get("order") or "").strip()
    if order:
        cmd += ["--order", order]

    where = (request.args.get("where") or "").strip()
    if where:
        cmd += ["--where", where]

    payload = _run_cli(cmd)
    items = _extract_items(payload)

    if bu_name:
        items = [
            x for x in items
            if isinstance(x, dict)
            and isinstance(x.get("businessunit"), dict)
            and (x["businessunit"].get("orgname") == bu_name)
        ]

    # Opcional: ordenar local por listorder si viene
    def _listorder(x: Dict[str, Any]) -> int:
        try:
            return int(x.get("listorder") or 0)
        except Exception:
            return 0

    items = sorted(items, key=_listorder)

    return jsonify({"status": "ok", "count": len(items), "trackingcentres": items})
