#!/usr/bin/env python3
"""Minimal Polysia webhook receiver for local tests (stdlib only).

Usage:  read -rs POLYSIA_WEBHOOK_SECRET; export POLYSIA_WEBHOOK_SECRET
        python3 -I polysia_webhook_receiver.py [port]      (default 9900, listens on 127.0.0.1)

It verifies every request (HMAC-SHA256 of "<Polysia-Timestamp>.<raw body>", 5 minute window),
de-duplicates on the event id, prints one line per event and answers 200 (400 if unverified).
Events can arrive out of order: always act on data.status (or GET /v1/invoices/{id}), never on order.
"""
import hashlib, hmac, json, os, sys, time
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ.get("POLYSIA_WEBHOOK_SECRET", "").encode()
TOLERANCE = 300
seen = set()


def verified(ts: str, header: str, body: bytes) -> bool:
    if not ts.isdigit() or abs(time.time() - int(ts)) > TOLERANCE:
        return False
    expected = hmac.new(SECRET, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
    for part in header.split(","):
        part = part.strip()
        if part.startswith("v1=") and hmac.compare_digest(part[3:], expected):
            return True
    return False


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", "0")))  # RAW bytes: verify before parsing
        ts = self.headers.get("Polysia-Timestamp", "")
        ok = verified(ts, self.headers.get("Polysia-Signature", ""), body)
        stamp = time.strftime("%H:%M:%S")
        if not ok:
            print(f"{stamp} REJECTED (bad signature or timestamp)", flush=True)
            self.send_response(400); self.end_headers(); return
        event = json.loads(body)
        data = event.get("data", {})
        dup = event["id"] in seen
        seen.add(event["id"])
        print(f"{stamp} signature OK  {event['id']}  {event['type']:<22} "
              f"{data.get('id', '')} status={data.get('status', '-')} amount={data.get('amount', '-')}"
              f"{'  (duplicate — already processed, ignored)' if dup else ''}", flush=True)
        self.send_response(200); self.end_headers(); self.wfile.write(b"ok")

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    if not SECRET:
        sys.exit("set POLYSIA_WEBHOOK_SECRET first (read -rs POLYSIA_WEBHOOK_SECRET; export POLYSIA_WEBHOOK_SECRET)")
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 9900
    print(f"listening on http://127.0.0.1:{port}/polysia", flush=True)
    HTTPServer(("127.0.0.1", port), Handler).serve_forever()
