#!/usr/bin/env python3
"""Bounded ingress probe for an isolated loopback deployment; never creates sessions."""
import argparse
import concurrent.futures
import ipaddress
import json
from collections import Counter
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlparse
from urllib.request import Request, urlopen

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", required=True)
parser.add_argument("--token-file", type=Path, required=True)
args = parser.parse_args()
url = urlparse(args.base_url)
try:
    local = ipaddress.ip_address(url.hostname or "").is_loopback
except ValueError:
    local = False
if url.scheme != "http" or not local or url.username or url.password or url.path not in ("", "/"):
    parser.error("Use the HTTP root of a separate loopback rehearsal deployment.")
token = args.token_file.read_text().strip()
body = b'{"flow":"demo-flow"}'

def request_once(_):
    request = Request(args.base_url.rstrip("/") + "/execkernel/graph/inspect", body,
                      {"Authorization": "Bearer " + token, "Content-Type": "application/json"})
    try:
        response = urlopen(request, timeout=15)
    except HTTPError as error:
        response = error
    with response:
        return response.status, json.loads(response.read())

with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
    responses = list(pool.map(request_once, range(80)))
counts = Counter(status for status, _ in responses)
sample = next((body for status, body in responses if status == 429), None)
print(json.dumps({"requests": 80, "status_counts": dict(sorted(counts.items())),
                  "sample_429": sample}, indent=2))
if not counts[200] or not counts[429]:
    raise SystemExit("The probe did not observe both admission and limiting; inspect ingress and timing.")
if set(counts) - {200, 429}:
    raise SystemExit("Unexpected statuses occurred; inspect them before interpreting this as a rate check.")
