#!/usr/bin/env python3
import os, sys, importlib.util, traceback, time, shutil, re, builtins

INBOX = os.environ.get("INBOX", "/Eden/CORE/phi_fractal")
QUAR  = os.environ.get("QUAR",  "/Eden/CORE/quarantine")
LOGF  = os.environ.get("LOGF",  "/Eden/LOGS/capability_guardian.log")

# Block network during smoke tests by stubbing common libs if present
def _stub_network():
    try:
        import socket
        def blocked(*a, **k): raise RuntimeError("Network blocked in smoke test")
        socket.socket = blocked  # coarse but effective
    except Exception: pass
    for modname in ("requests","urllib","urllib3"):
        sys.modules[modname] = type("X", (), {})()

CAP_PAT = re.compile(r"eden_capability_.*\.py$")
NEW_CAPS = []

for root, _, files in os.walk(INBOX):
    for f in files:
        if CAP_PAT.match(f):
            NEW_CAPS.append(os.path.join(root, f))

NEW_CAPS.sort(key=lambda p: os.path.getmtime(p), reverse=True)
NEW_CAPS = NEW_CAPS[:20]  # limit to most recent 20

os.makedirs(os.path.dirname(LOGF), exist_ok=True)
log = open(LOGF, "a", encoding="utf-8")
print(f"[{time.strftime('%F %T')}] Guardian scanning {len(NEW_CAPS)} files", file=log)

def smoke_import(path):
    name = os.path.splitext(os.path.basename(path))[0]
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    _stub_network()
    try:
        spec.loader.exec_module(mod)  # may run top-level code; that's the point
        return True, None
    except Exception as e:
        return False, "".join(traceback.format_exception(e))

failed = []
for p in NEW_CAPS:
    ok, err = smoke_import(p)
    if ok:
        print(f"✓ IMPORT OK  {p}", file=log)
    else:
        print(f"✗ IMPORT FAIL {p}\n{err}", file=log)
        # quarantine the file
        rel = os.path.relpath(p, INBOX).replace(os.sep, "_")
        dest = os.path.join(QUAR, f"{rel}.{int(time.time())}")
        os.makedirs(os.path.dirname(dest), exist_ok=True)
        shutil.move(p, dest)
        failed.append((p, dest))

print(f"[{time.strftime('%F %T')}] Done. Failed: {len(failed)}", file=log)
log.close()

# Print concise summary to stdout
if failed:
    print("❌ Some capabilities failed import and were quarantined:")
    for src, dst in failed:
        print(f" - {src}  →  {dst}")
    sys.exit(2)
else:
    print("✅ All recent capabilities imported cleanly (network blocked in test).")
