"""Local HTTP test. Run after starting php -S 127.0.0.1:8080 -t public."""
import json
import os
import urllib.error
import urllib.request
import http.cookiejar

BASE = os.getenv('AGENT_TEST_URL', 'http://127.0.0.1:8080')
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))

def call(path, data=None, csrf=None):
    headers = {}
    if data is not None:
        headers['Content-Type'] = 'application/json'
        if csrf is not None:
            headers['X-CSRF-Token'] = csrf
        data = json.dumps(data).encode()
    req = urllib.request.Request(BASE + path, data=data, headers=headers)
    try:
        resp = opener.open(req, timeout=5)
    except urllib.error.HTTPError as exc:
        resp = exc
    body = resp.read().decode()
    return resp.status, json.loads(body) if path.startswith('/api.php') else body

status, html = call('/')
assert status == 200 and 'Reflexive Agent' in html and 'Studio.' in html, (status, html[:100])
print('PASS: UI HTML')
status, data = call('/api.php?action=bootstrap')
assert status == 200 and data['ok'] and len(data['csrf']) == 64
print('PASS: session bootstrap')
csrf = data['csrf']
status, _ = call('/api.php', {'action': 'reset'})
assert status == 403
print('PASS: CSRF rejection')
status, data = call('/api.php', {'action': 'preview', 'state': 'wild', 'message': '<hello>&'}, csrf)
assert status == 200 and '&lt;hello&gt;&amp;' in data['user']
print('PASS: validated prompt preview')
status, data = call('/api.php', {'action': 'reset'}, csrf)
assert status == 200 and len(data['csrf']) == 64 and data['csrf'] != csrf
print('PASS: new conversation and CSRF rotation')
print('All local HTTP tests passed. Claude API not called.')
