import ast
import py_compile
import sys
from pathlib import Path

BASE = Path("/var/www/html/NFL_ST")

ARCHIVOS = [
    "nfl.py",
    "hermes_api.py",
    "hermes_brain.py",
    "hermes_brain_v2.py",
    "hermes_tools.py",
    "hermes_memory.py",
    "hermes_web.py",
    "hermes_epg.py",
    "hermes_epg_search.py",
    "hermes_speech_cleaner.py"
]

def validar():
    errores = []

    print("=== HERMES SAFE DEPLOY ===")

    for nombre in ARCHIVOS:
        ruta = BASE / nombre

        if not ruta.is_file():
            errores.append(f"{nombre}: archivo inexistente")
            continue

        contenido = ruta.read_text(encoding="utf-8")

        if not contenido.strip():
            errores.append(f"{nombre}: archivo vacio")
            continue

        try:
            ast.parse(contenido, filename=nombre)
            py_compile.compile(str(ruta), doraise=True)
            print("OK:", nombre)
        except Exception as e:
            errores.append(f"{nombre}: {type(e).__name__}")

    # Comprobar que nfl.py conserva su aplicacion FastAPI
    principal = BASE / "nfl.py"

    if principal.is_file():
        try:
            arbol = ast.parse(
                principal.read_text(encoding="utf-8")
            )

            existe_app = any(
                isinstance(n, ast.Assign)
                and any(
                    isinstance(t, ast.Name) and t.id == "app"
                    for t in n.targets
                )
                for n in arbol.body
            )

            if not existe_app:
                errores.append("nfl.py: falta declaracion app")

        except Exception:
            pass

    if errores:
        print("\nVALIDACION FALLIDA")
        for error in errores:
            print("ERROR:", error)
        return False

    print("\nCODIGO VALIDADO")
    return True


if __name__ == "__main__":
    sys.exit(0 if validar() else 1)
