#!/usr/bin/env python3
"""Deploy mail-bundle endpoint na VM112 — executar NO host (Spec 035/043).

Uso (a partir do clone ligbox-ops-platform na VM112 ou CT130 com scp):
  REPO=/opt/ligbox-spec-hub/repos/ligbox-ops-platform
  python3 $REPO/deploy/vm112-wizard/deploy-mail-bundle-vm112.py
  systemctl restart ligbox-wizard
"""
from __future__ import annotations

import ast
import shutil
import sys
from pathlib import Path

REPO = Path(sys.argv[1] if len(sys.argv) > 1 else "/opt/ligbox-spec-hub/repos/ligbox-ops-platform")
WIZARD = Path("/opt/ligbox-wizard")
SRC_SVC = REPO / "projects/wizard/backend/app/services/mail_bundle.py"
SRC_ROUTER = REPO / "projects/wizard/backend/app/routers/internal_provision.py"
DST_SVC = WIZARD / "backend/app/services/mail_bundle.py"
DST_ROUTER = WIZARD / "backend/app/routers/internal_provision.py"
MAIN = WIZARD / "backend/app/main.py"

if not WIZARD.is_dir():
    print("ERRO: /opt/ligbox-wizard não encontrado — executar na VM112")
    sys.exit(1)
if not SRC_SVC.is_file():
    print(f"ERRO: fonte não encontrada: {SRC_SVC}")
    sys.exit(1)

shutil.copy2(SRC_SVC, DST_SVC)
shutil.copy2(SRC_ROUTER, DST_ROUTER)
print("copied mail_bundle.py + internal_provision.py")

text = MAIN.read_text(encoding="utf-8")

if "internal_provision" not in text:
    old = "    telemetry,\n)"
    new = "    telemetry,\n    internal_provision,\n)"
    if old in text:
        text = text.replace(old, new)
    else:
        text = text.replace(
            "from app.routers import",
            "from app.routers import internal_provision,",
            1,
        )

if "internal_provision.router" not in text:
    anchor = 'app.include_router(onboarding.router, prefix="/api")'
    if anchor in text:
        text = text.replace(
            anchor,
            anchor + '\napp.include_router(internal_provision.router, prefix="/api")',
        )
    else:
        text = text.rstrip() + '\napp.include_router(internal_provision.router, prefix="/api")\n'

MAIN.write_text(text, encoding="utf-8")
ast.parse(text)
print("main.py patched")
print("OK — reiniciar: systemctl restart ligbox-wizard")
