"""Local test site for the Playwright MCP test (2026-10-26). Logs every POST as JSON lines to posts.jsonl.
/order returns a confirmation page with a code derived from the submitted data (sha256 of the sorted fields, first 8 hex)."""
import hashlib, json, sys, time, urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
LOG = sys.argv[2] if len(sys.argv) > 2 else "posts.jsonl"
PAGE = open(__file__.rsplit('/',1)[0] + "/site/index.html", "rb").read()
class H(BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def _send(self, body, code=200):
        self.send_response(code); self.send_header("Content-Type", "text/html; charset=utf-8"); self.end_headers(); self.wfile.write(body)
    def do_GET(self):
        self._send(PAGE if self.path in ("/", "/index.html") else b"<h1>Help</h1><p>Call us.</p>")
    def do_POST(self):
        n = int(self.headers.get("Content-Length", 0)); raw = self.rfile.read(n).decode()
        fields = {k: v[0] if len(v) == 1 else v for k, v in urllib.parse.parse_qs(raw, keep_blank_values=True).items()}
        code = hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()[:8].upper()
        with open(LOG, "a") as f: f.write(json.dumps({"t": time.time(), "path": self.path, "fields": fields, "code": code}) + "\n")
        if self.path == "/order":
            self._send(f"<h1>Order received</h1><p>Your confirmation code is <strong>{code}</strong>.</p>".encode())
        else:
            self._send(b"<h1>Thanks for subscribing</h1>")
ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
