#!/usr/bin/env python3
"""Minimal webhook receiver with signature check and duplicate protection — lesson AUT-201-L05.

Listens on http://127.0.0.1:8788/hooks/orders . Standard library only. For local practice only.

Checks, in order:
  1. Content-Type is JSON and body size is reasonable
  2. X-Signature-256 == "sha256=" + HMAC-SHA256(secret, raw body)   (constant-time compare)
  3. event_id not seen before (duplicate deliveries are acknowledged but not processed again)
Then it answers 200 quickly and "processes" the event (here: prints a one-line summary).

    # Linux/macOS                                   # Windows PowerShell
    export WEBHOOK_SECRET=practice-secret-change-me  $env:WEBHOOK_SECRET = "practice-secret-change-me"
    python webhook_receiver.py
"""
import hashlib
import hmac
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ.get("WEBHOOK_SECRET")
MAX_BODY = 64 * 1024
seen_events = set()  # in production this must be durable storage, not memory


class Hook(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def reply(self, status, text):
        body = json.dumps({"result": text}).encode()
        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)
        print(f"{status} {text}")

    def do_POST(self):
        if self.path != "/hooks/orders":
            return self.reply(404, "unknown path")
        if "application/json" not in (self.headers.get("Content-Type") or ""):
            return self.reply(415, "expected JSON")
        length = int(self.headers.get("Content-Length") or 0)
        if length > MAX_BODY:
            return self.reply(413, "body too large")
        raw = self.rfile.read(length)  # verify the RAW bytes, before any parsing
        expected = "sha256=" + hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest()
        given = self.headers.get("X-Signature-256", "")
        if not hmac.compare_digest(expected, given):
            return self.reply(401, "bad signature: ignored")
        try:
            event = json.loads(raw.decode("utf-8"))
        except (UnicodeDecodeError, json.JSONDecodeError):
            return self.reply(400, "invalid JSON")
        eid = event.get("event_id")
        if not eid:
            return self.reply(400, "missing event_id")
        if eid in seen_events:
            return self.reply(200, f"duplicate {eid}: acknowledged, not processed again")
        seen_events.add(eid)
        self.reply(200, f"accepted {eid}")
        # quick ack first; real work (calling other APIs, models) would go to a queue
        print(f"   processing {event.get('type')} order={event.get('data', {}).get('order_id')}")


if __name__ == "__main__":
    if not SECRET:
        sys.exit("set WEBHOOK_SECRET first (any practice value; never a real secret in examples)")
    print("webhook receiver on http://127.0.0.1:8788/hooks/orders")
    HTTPServer(("127.0.0.1", 8788), Hook).serve_forever()
