import http.client
import json
from pathlib import Path


def check(path, status, body, headers=None):
    connection = http.client.HTTPConnection("127.0.0.1", 8080, timeout=5)
    try:
        connection.request("GET", path, headers=headers or {})
        response = connection.getresponse()
        if response.status != status or response.read() != body:
            raise ValueError()
    finally:
        connection.close()


def main():
    runtime = Path(__file__).resolve().parent / ".runtime" / "app.json"
    token = json.loads(runtime.read_text(encoding="utf-8"))["api_token"]
    if not isinstance(token, str) or not token:
        raise ValueError()
    if any(ord(char) < 33 or ord(char) > 126 for char in token):
        raise ValueError()

    check("/healthz", 200, b"ok\n")
    check("/private", 401, b"unauthorized\n")
    check("/private", 401, b"unauthorized\n", {"Authorization": "Bearer " + token + "x"})
    check("/private", 200, b"authorized\n", {"Authorization": "Bearer " + token})
    print("PASS: health, missing bearer, incorrect bearer, and valid bearer")


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, TypeError, KeyError, http.client.HTTPException):
        raise SystemExit("Verification failed; check startup, file access, and configuration") from None
