"""
Modify observer script to dump the actual DOM structure around detected buttons
and bot message containers. Write results to bridge/dom_structure.json
"""
import requests, json

BASE = "http://127.0.0.1:34332"

# The trick: use test-rpc endpoint to NOT call an RPC, but instead
# post a probe via the /dump-html endpoint that our observer script 
# will see as content.

# Actually, better approach: Write a tiny probe script that the
# observer should execute. But we can't inject new scripts at runtime.

# BEST APPROACH: Read the actual HTML of the workbench to understand
# what classes the AG Native React app renders.

# Check the AG main JS files to understand class names
import os, re

ag_base = r"C:\Users\Variet-Worker\AppData\Local\Programs\Antigravity\resources\app\out"

# The jetski agent JS is the main entry point
jetski_dir = os.path.join(ag_base, "vs", "code", "electron-browser", "workbench")

# Search for CSS class patterns in the built JS
# Look for message/chat/conversation related classes
search_patterns = [
    r'message[-_]block',
    r'bot[-_](?:message|color|response|turn)',
    r'agent[-_](?:convo|message|response)',
    r'chat[-_](?:body|message|content)',
    r'markdown[-_]body',
    r'text[-_]ide',
    r'(?:pending|approval|approve)[-_]',
    r'actions[-_]container',
    r'tool[-_](?:call|action|result)',
]

# Search in the jetski JS bundle
js_files = []
for root, dirs, files in os.walk(ag_base):
    for f in files:
        if f.endswith('.js') and ('jetski' in f.lower() or 'agent' in f.lower()):
            js_files.append(os.path.join(root, f))
    # Don't recurse too deep
    if root.count(os.sep) - ag_base.count(os.sep) > 5:
        dirs.clear()

print(f"Found {len(js_files)} jetski/agent JS files")
for jf in js_files[:10]:
    print(f"  {os.path.relpath(jf, ag_base)}: {os.path.getsize(jf)} bytes")

# Search the main jetski bundle for relevant class patterns
main_js = os.path.join(jetski_dir, "jetskiAgent.js")
if os.path.exists(main_js):
    content = open(main_js, encoding='utf-8', errors='replace').read()
    print(f"\njetskiAgent.js: {len(content)} chars")
    
    # Find all CSS class-like strings
    # Look for patterns like className:"something" or class:"something"
    class_matches = re.findall(r'(?:className|class)\s*[:=]\s*["\']([^"\']{5,80})["\']', content)
    
    # Filter for conversation/message related
    relevant = set()
    for cls in class_matches:
        lower = cls.lower()
        if any(kw in lower for kw in ['message', 'chat', 'bot', 'agent', 'response', 
                                        'markdown', 'convo', 'turn', 'approval',
                                        'pending', 'action', 'tool', 'content',
                                        'text-ide', 'block']):
            relevant.add(cls)
    
    print(f"\nRelevant CSS classes ({len(relevant)}):")
    for cls in sorted(relevant)[:50]:
        print(f"  .{cls}")
    
    # Also search for data-testid patterns
    testid_matches = re.findall(r'data-testid\s*[:=]\s*["\']([^"\']+)["\']', content)
    if testid_matches:
        print(f"\ndata-testid values ({len(testid_matches)}):")
        for tid in sorted(set(testid_matches))[:30]:
            print(f"  [{tid}]")
    
    # Search for the specific bot/assistant message container patterns  
    for pat in search_patterns:
        matches = re.findall(f'["\']([^"\']*{pat}[^"\']*)["\']', content, re.IGNORECASE)
        if matches:
            unique = sorted(set(matches))[:5]
            print(f"\n  Pattern '{pat}': {unique}")

else:
    print(f"\njetskiAgent.js NOT FOUND at {main_js}")
