#!/usr/bin/env python3
"""Garante list_all_domains() em carbonio.py na VM112 (Serviços IaaS / Spec 017).

Executar NA VM112 após patches que sobrescrevem carbonio.py sem gad cache.
  python3 ensure-carbonio-list-domains.py
  systemctl restart ligbox-wizard
"""
from __future__ import annotations

from pathlib import Path

PATH = Path("/opt/ligbox-wizard/backend/app/services/carbonio.py")
MARKER = "\ndef set_domain_public_hostname(domain: str) -> str:"
INSERT = '''

def list_all_domains(*, use_cache: bool = True) -> list[str]:
    """zmprov gad (~5s) — cache TTL curto para Serviços IaaS / Desk."""
    cache_key = carbonio_cache.CACHE_KEY_ALL_DOMAINS
    if use_cache:
        cached = carbonio_cache.get(cache_key)
        if cached is not None:
            return list(cached)
    code, out, _err = _zmprov_run("gad", log_cmd=False)
    if code != 0:
        return []
    domains = [ln.strip().lower() for ln in out.splitlines() if ln.strip()]
    if use_cache:
        carbonio_cache.set(cache_key, domains, carbonio_cache.TTL_ALL_DOMAINS)
    return domains


def invalidate_domain_list_cache() -> None:
    carbonio_cache.invalidate_all_domains()

'''


def main() -> None:
    if not PATH.is_file():
        raise SystemExit(f"ERRO: {PATH} não encontrado — executar na VM112")
    text = PATH.read_text(encoding="utf-8")
    if "def list_all_domains" in text:
        print("OK — list_all_domains já presente")
        return
    if MARKER not in text:
        raise SystemExit("ERRO: marker set_domain_public_hostname não encontrado")
    PATH.write_text(text.replace(MARKER, INSERT + MARKER, 1), encoding="utf-8")
    print("OK — list_all_domains inserido; reiniciar: systemctl restart ligbox-wizard")


if __name__ == "__main__":
    main()
