"""
Deployment verification — tests that all components respond.
Run: uv run python tests/verify_deploy.py
"""
import sys, os, json, urllib.request

ALL_OK = True

def check(name, ok, detail=""):
    global ALL_OK
    if ok:
        print(f"  [OK] {name}")
    else:
        print(f"  [FAIL] {name}  {detail}")
        ALL_OK = False

print("=== AgentsMeeting Deployment Verification ===")
print()

# 1. xmpp_bot process
import subprocess
r = subprocess.run(['tasklist', '/FO', 'CSV', '/NH'],
                   capture_output=True, text=True, timeout=10)
found = False
for line in r.stdout.splitlines():
    if 'python.exe' in line:
        pid = line.split('","')[1].strip().strip('"')
        try:
            wmi = subprocess.run(['wmic', 'process', 'where', f'ProcessId={pid}',
                                 'get', 'CommandLine', '/format:list'],
                                capture_output=True, text=True, timeout=5)
            if 'xmpp_bot' in wmi.stdout and 'watchdog' not in wmi.stdout:
                found = True
                break
        except: pass
check("xmpp_bot process", found)

# 2. HTTP bridge
try:
    resp = urllib.request.urlopen("http://127.0.0.1:5802/messages", timeout=5)
    data = json.loads(resp.read())
    check("HTTP bridge (:5802)", data.get("ok") == True, str(data.get("error", "")))
except Exception as e:
    check("HTTP bridge (:5802)", False, str(e))

# 3. Send API
try:
    body = json.dumps({"message": "deploy verify test"}).encode()
    req = urllib.request.Request("http://127.0.0.1:5802/send", data=body,
                                 headers={"Content-Type": "application/json"})
    resp = urllib.request.urlopen(req, timeout=5)
    data = json.loads(resp.read())
    check("HTTP bridge send", data.get("ok") == True, str(data))
except urllib.error.HTTPError as e:
    detail = e.read().decode()
    check("HTTP bridge send", False, f"HTTP {e.code}: {detail}")
except Exception as e:
    check("HTTP bridge send", False, str(e))

# 4. Health check log exists
log = os.path.expanduser("~/.local/share/opencode/opencode.db")
check("opencode.db exists", os.path.exists(log))

# 5. Project structure
project = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
required = [
    "docs/ARCHITECTURE.md", "docs/DEPLOY.md", "docs/OPS.md",
    "deploy/windows/start.ps1", "deploy/windows/check.ps1",
    "src/shared/config.py", "src/shared/bot_base.py",
    "tests/test_core.py",
]
for f in required:
    check(f, os.path.exists(os.path.join(project, f)))

print()
if ALL_OK:
    print("=== ALL CHECKS PASSED ===")
else:
    print("=== SOME CHECKS FAILED ===")
