"""A partner's webhook endpoint, for the demo: verifies, deduplicates, and fails once on purpose."""
import hmac
import json
import os
import time
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException, Request

from orders_api.outbox import sign

app = FastAPI()
SECRET = os.environ["ORDERS_WEBHOOK_SECRET"]
accepted: dict[str, dict] = {}
log: list[str] = []
fail_once = {"evt_1"}                     # pretend to be down for the very first delivery


@app.post("/webhooks", status_code=204)
async def receive(request: Request,
                  webhook_id: Annotated[str, Header()],
                  webhook_timestamp: Annotated[str, Header()],
                  webhook_signature: Annotated[str, Header()]) -> None:
    body = (await request.body()).decode()
    expected = sign(SECRET, webhook_id, webhook_timestamp, body)
    if not hmac.compare_digest(webhook_signature, expected):            # constant-time comparison
        log.append(f"{webhook_id}: bad signature -> 401")
        raise HTTPException(401)
    if abs(time.time() - int(webhook_timestamp)) > 300:                 # replay protection
        log.append(f"{webhook_id}: stale timestamp -> 400")
        raise HTTPException(400)
    if webhook_id in fail_once:
        fail_once.discard(webhook_id)
        log.append(f"{webhook_id}: receiver 'down' -> 503")
        raise HTTPException(503)
    if webhook_id in accepted:                                          # at-least-once: deduplicate
        log.append(f"{webhook_id}: duplicate, ignored")
        return
    event = json.loads(body)
    accepted[webhook_id] = event
    log.append(f"{webhook_id}: accepted {event['type']} order {event['orderId']} -> {event['status']}")


@app.get("/received")
def received() -> dict:
    return {"accepted": len(accepted), "log": log}
