"""Test AG SDK RPC to understand what data is available for current session."""
import requests, json, sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')

BASE = "http://127.0.0.1:34332"
SESSION = "bdfc07d3-d87e-453a-b785-e38c2e9254e3"

def rpc(method, args=None):
    r = requests.post(f"{BASE}/test-rpc", json={"method": method, "args": args or {}})
    if r.status_code != 200:
        print(f"❌ {method}: {r.status_code} - {r.text[:200]}")
        return None
    try:
        return r.json()
    except:
        print(f"❌ {method}: non-JSON response: {r.text[:200]}")
        return None

# 1. Try GetCascadeTrajectorySteps for current session
print("=== GetCascadeTrajectorySteps ===")
result = rpc("GetCascadeTrajectorySteps", {"cascadeId": SESSION, "verbosity": 1})
if result and "steps" in result:
    steps = result["steps"]
    print(f"  Got {len(steps)} steps")
    for i, s in enumerate(steps[-5:]):
        print(f"  Step {i}: type={s.get('type','?')} status={s.get('status','?')}")
        if s.get('plannerResponse'):
            pr = s['plannerResponse']
            if isinstance(pr, str):
                print(f"    plannerResponse (str): {pr[:100]}...")
            elif isinstance(pr, dict):
                print(f"    plannerResponse keys: {list(pr.keys())}")
                for k, v in pr.items():
                    if isinstance(v, str) and len(v) > 20 and k not in ('thinking', 'thinkingSignature'):
                        print(f"    {k}: {v[:100]}...")
else:
    print("  No steps returned")

# 2. Try GetDiagnostics
print("\n=== GetDiagnostics ===")
diag = rpc("GetDiagnostics", {})
if diag:
    if isinstance(diag, str):
        diag = json.loads(diag)
    recent = diag.get("recentTrajectories", [])
    print(f"  recentTrajectories: {len(recent)}")
    for rt in recent:
        sid = rt.get("googleAgentId", "?")
        if sid.startswith("bdfc"):
            print(f"  ★ Current session: {json.dumps(rt, indent=2)[:500]}")

# 3. Try GetAllCascadeTrajectories looking for our session
print("\n=== GetAllCascadeTrajectories ===")
traj = rpc("GetAllCascadeTrajectories", {"limit": 100, "descending": True})
if traj and "trajectorySummaries" in traj:
    summaries = traj["trajectorySummaries"]
    print(f"  Total trajectories: {len(summaries)}")
    for sid, data in summaries.items():
        if sid.startswith("bdfc"):
            print(f"  ★ Current session keys: {list(data.keys())}")
            print(f"    status: {data.get('status')}")
            print(f"    stepCount: {data.get('stepCount')}")
            print(f"    latestNotifyUserStep: {json.dumps(data.get('latestNotifyUserStep'), indent=2)[:300] if data.get('latestNotifyUserStep') else 'None'}")
            print(f"    latestTaskBoundaryStep: {json.dumps(data.get('latestTaskBoundaryStep'), indent=2)[:300] if data.get('latestTaskBoundaryStep') else 'None'}")

# 4. Try other RPC methods that might exist
print("\n=== Trying alternative RPCs ===")
for method in ["GetCascadeStatus", "GetAgentStatus", "ListCascades", "GetCascadeInfo"]:
    result = rpc(method, {"cascadeId": SESSION})
    if result:
        print(f"  {method}: {json.dumps(result)[:200]}")
