"""Minimal webhook receiver: verify the HMAC signature, then notify a Slack channel.

FilingPulse signs every delivery with your subscription's secret
(X-FilingPulse-Signature: sha256=...). ALWAYS verify before trusting a payload —
anyone can POST JSON at your endpoint; only FilingPulse knows the secret.

Setup:
    1. Create a subscription (docs: /docs.html#webhooks) pointing at this server.
    2. export FILINGPULSE_WEBHOOK_SECRET=whsec_...   # shown once at creation
    3. Optional: export SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
       (without it, deliveries are printed to stdout only)
    4. python webhook_receiver.py --port 8080

Requires: pip install filingpulse   (stdlib otherwise)
"""
import argparse
import json
import os
import sys
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

from filingpulse import verify_webhook_signature

SECRET = os.environ.get("FILINGPULSE_WEBHOOK_SECRET")
SLACK_URL = os.environ.get("SLACK_WEBHOOK_URL")


def summarize(delivery: dict) -> str:
    """One factual line per delivery. Descriptive only — no interpretation."""
    event, filing = delivery.get("event"), delivery.get("data", {})
    issuer = (filing.get("issuer") or {}).get("name", "?")
    if event == "filing.form4":
        owners = ", ".join(o["name"] for o in filing.get("reporting_owners", []))
        codes = ",".join(sorted({t["transaction_code"] for t in
                                 filing.get("transactions", [])} - {None}))
        return f"Form {filing.get('form_type')}: {owners} @ {issuer} (codes: {codes or 'holdings only'})"
    if event == "filing.8k":
        items = ", ".join(i["code"] for i in filing.get("items", []))
        return f"8-K: {issuer} (items {items})"
    if event == "filing.registration":
        return (f"{filing.get('form_type')} [{filing.get('stage')}]: {issuer} "
                f"(file {filing.get('file_number')})")
    return f"{event}: {issuer}"


def notify(line: str) -> None:
    print(line, flush=True)
    if SLACK_URL:
        req = urllib.request.Request(
            SLACK_URL, data=json.dumps({"text": line}).encode(),
            headers={"Content-Type": "application/json"})
        urllib.request.urlopen(req, timeout=10)


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        signature = self.headers.get("X-FilingPulse-Signature", "")
        if not verify_webhook_signature(SECRET, body, signature):
            self.send_response(400)
            self.end_headers()
            self.wfile.write(b"bad signature")
            return
        notify(summarize(json.loads(body)))
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"ok")

    def log_message(self, *args):  # signature check already logs what matters
        pass


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--port", type=int, default=8080)
    args = ap.parse_args()
    if not SECRET:
        sys.exit("Set FILINGPULSE_WEBHOOK_SECRET (shown once when you create the subscription)")
    print(f"Listening on :{args.port} — Slack forwarding "
          f"{'ON' if SLACK_URL else 'off (stdout only)'}", flush=True)
    HTTPServer(("", args.port), Handler).serve_forever()


if __name__ == "__main__":
    main()
