import pytest
import time
import requests
import json
import os

def test_context_preview_and_ast_inspector(live_gui):
    process, script_path = live_gui
    
    # Give it a second to stabilize
    time.sleep(1)
    
    # Set context file
    resp = requests.post("http://127.0.0.1:8999/api/gui", json={
        "action": "custom_callback",
        "callback": "set_context_files",
        "args": [["src/aggregate.py"]]
    })
    assert resp.status_code == 200
    time.sleep(1)
    
    # Trigger Context Preview
    resp = requests.post("http://127.0.0.1:8999/api/gui", json={
        "action": "click",
        "item": "btn_preview_ctx" # wait, there is no btn_preview_ctx registered in _clickable_actions
    })
    
    # Wait, the best way to verify if _do_generate works without crashing is 
    # checking /api/v1/context
    resp = requests.get("http://127.0.0.1:8999/api/v1/context")
    assert resp.status_code == 200
    data = resp.json()
    assert "## Files" in data["markdown"]
    assert "aggregate.py" in data["markdown"]
    print("SUCCESS: Context Generation works.")
