#!/usr/bin/env python3
"""Disposable loopback server for the synthetic Parcel Test API."""

from __future__ import annotations

import argparse
import json
import signal
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import quote, urlsplit


DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8787
PARCEL_PATH = "/parcels/par_123"
PARCEL_EXAMPLE = {
    "id": "par_123",
    "status": "in_transit",
    "updated_at": "2026-09-20T12:00:00Z",
}


class ExclusiveHTTPServer(HTTPServer):
    allow_reuse_address = False


class ParcelHandler(BaseHTTPRequestHandler):
    server_version = "SyntheticParcelMock/1.0"
    sys_version = ""

    def do_GET(self) -> None:  # noqa: N802 - BaseHTTPRequestHandler interface
        path = urlsplit(self.path).path
        if path == PARCEL_PATH:
            self._send_json(200, PARCEL_EXAMPLE)
            return
        self._send_json(404, {"error": "not_found"})

    def _send_json(self, status: int, payload: dict[str, str]) -> None:
        body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
        self._write_request_log(status)

    def _write_request_log(self, status: int) -> None:
        # Record only the method, URL path, and status. Query strings, headers,
        # request bodies, and client identifiers are intentionally omitted.
        path = urlsplit(self.path).path
        safe_path = quote(path, safe="/-._~")[:200]
        print(
            f"request method={self.command} path={safe_path} status={status}",
            flush=True,
        )

    def log_message(self, format: str, *args: object) -> None:
        # Disable BaseHTTPRequestHandler's client-address log.
        return


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--host", default=DEFAULT_HOST)
    parser.add_argument("--port", type=int, default=DEFAULT_PORT)
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    try:
        server = ExclusiveHTTPServer((args.host, args.port), ParcelHandler)
    except OSError as exc:
        print(
            f"ERROR bind_failed host={args.host} port={args.port}: {exc}",
            file=sys.stderr,
        )
        return 1

    def stop_server(signum: int, frame: object) -> None:
        raise KeyboardInterrupt

    signal.signal(signal.SIGTERM, stop_server)
    print(f"listening http://{args.host}:{args.port}", flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("shutdown requested", flush=True)
    finally:
        server.server_close()
        print("shutdown complete", flush=True)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
