"""Small durable inbox example. Run behind HTTPS; process accepted rows separately.

uv run uvicorn examples.webhook_receiver:create_app --factory --host 127.0.0.1 --port 8081
Required environment: SPARKINN_WEBHOOK_SECRET, SPARKINN_WEBHOOK_TENANT_ID,
SPARKINN_WEBHOOK_PROPERTY_IDS (comma separated). Optional SPARKINN_WEBHOOK_INBOX.
No payment, access-device or booking side effects are performed by this example.
"""

import base64
import hashlib
import hmac
import json
import os
import sqlite3
import time
from pathlib import Path
from uuid import UUID

from fastapi import FastAPI, HTTPException, Request


def create_app(*, secret=None, tenant_id=None, property_ids=None, inbox=None):
    secret = secret or os.environ["SPARKINN_WEBHOOK_SECRET"]
    tenant_id = str(UUID(tenant_id or os.environ["SPARKINN_WEBHOOK_TENANT_ID"]))
    property_ids = {
        str(UUID(p.strip()))
        for p in (property_ids or os.environ["SPARKINN_WEBHOOK_PROPERTY_IDS"].split(","))
    }
    signing_key = base64.b64decode(secret.removeprefix("whsec_"), validate=True)
    if len(signing_key) < 32 or not property_ids:
        raise ValueError("Configure the endpoint secret and explicit property scope")
    inbox = Path(inbox or os.environ.get("SPARKINN_WEBHOOK_INBOX", "webhook-inbox.sqlite3"))
    inbox.parent.mkdir(parents=True, exist_ok=True)
    # Create privately; deployment owns the enclosing directory and backup policy.
    fd = os.open(inbox, os.O_CREAT | os.O_WRONLY, 0o600)
    os.close(fd)
    with sqlite3.connect(inbox) as db:
        db.execute(
            "CREATE TABLE IF NOT EXISTS inbox (event_id TEXT PRIMARY KEY, digest TEXT NOT NULL, "
            "body BLOB NOT NULL, received_at INTEGER NOT NULL, processed_at INTEGER)"
        )
    app = FastAPI(title="SparkInn webhook receiver example")

    @app.post("/sparkinn/events", status_code=202)
    async def accept(request: Request):
        event_id = request.headers.get("webhook-id", "")
        timestamp = request.headers.get("webhook-timestamp", "")
        signatures = request.headers.get("webhook-signature", "")
        try:
            if len(timestamp) > 16 or abs(time.time() - int(timestamp)) > 300:
                raise ValueError()
            if str(UUID(event_id)) != event_id:
                raise ValueError()
        except ValueError:
            raise HTTPException(401, "Invalid webhook time or identifier") from None
        if len(signatures) > 2048:
            raise HTTPException(401, "Invalid webhook signature")
        raw = bytearray()
        async for part in request.stream():
            raw.extend(part)
            if len(raw) > 65536:
                raise HTTPException(413, "Webhook too large")
        raw = bytes(raw)
        expected = (
            "v1,"
            + base64.b64encode(
                hmac.new(
                    signing_key,
                    f"{event_id}.{timestamp}.".encode() + raw,
                    hashlib.sha256,
                ).digest()
            ).decode()
        )
        if not any(hmac.compare_digest(s, expected) for s in signatures.split() if s.isascii()):
            raise HTTPException(401, "Invalid webhook signature")
        try:
            data = json.loads(raw)
        except (ValueError, UnicodeError):
            raise HTTPException(400, "Invalid JSON") from None
        if (
            not isinstance(data, dict)
            or data.get("event_id") != event_id
            or data.get("schema_version") != 1
        ):
            raise HTTPException(400, "Unsupported webhook envelope")
        if data.get("tenant_id") != tenant_id or data.get("property_id") not in property_ids:
            raise HTTPException(403, "Webhook outside configured scope")
        digest = hashlib.sha256(raw).hexdigest()
        with sqlite3.connect(inbox, timeout=5) as db:
            db.execute("BEGIN IMMEDIATE")
            previous = db.execute(
                "SELECT digest FROM inbox WHERE event_id=?", (event_id,)
            ).fetchone()
            if previous:
                if previous[0] != digest:
                    raise HTTPException(409, "Event identifier reused with different content")
                return {"accepted": True, "duplicate": True}
            db.execute(
                "INSERT INTO inbox(event_id,digest,body,received_at) VALUES(?,?,?,?)",
                (event_id, digest, raw, int(time.time())),
            )
        # 202 confirms a durable inbox write, not execution of a downstream action.
        return {"accepted": True, "duplicate": False}

    return app
