"""Webhook receiver with dedupe and a sync log.

POST /webhook accepts an event ID plus a payload. The first delivery
is processed once and logged in SQLite. A repeat delivery with the
same event ID returns the recorded result without reprocessing. If
the downstream step fails, the log row is marked failed with its
attempt count, and a later delivery of the same event ID retries.

GET /sync-log returns the log rows so the state can be inspected.
GET /health returns a plain ok.

The downstream step is a stub: it fails when the payload carries
"fail": true, and succeeds otherwise. Swap process_event for a real
CRM or API call in production use.
"""

from __future__ import annotations

import os
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel


class WebhookIn(BaseModel):
    event_id: str
    payload: dict[str, Any]


def process_event(payload: dict[str, Any]) -> None:
    """Downstream stub. Raises when the payload asks it to fail."""
    if payload.get("fail"):
        raise RuntimeError("downstream rejected the event")


def _now() -> str:
    return datetime.now(timezone.utc).isoformat()


def create_app(
    db_path: str | Path,
    processor: Callable[[dict[str, Any]], None] = process_event,
) -> FastAPI:
    db_path = str(db_path)

    def connect() -> sqlite3.Connection:
        conn = sqlite3.connect(db_path)
        conn.row_factory = sqlite3.Row
        conn.execute(
            """
            CREATE TABLE IF NOT EXISTS sync_log (
                event_id TEXT PRIMARY KEY,
                status TEXT NOT NULL,
                attempts INTEGER NOT NULL,
                last_error TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            )
            """
        )
        return conn

    app = FastAPI(title="Webhook receiver")

    @app.get("/health")
    def health() -> dict:
        return {"status": "ok"}

    @app.post("/webhook")
    def receive(body: WebhookIn) -> dict:
        conn = connect()
        try:
            row = conn.execute(
                "SELECT * FROM sync_log WHERE event_id = ?", (body.event_id,)
            ).fetchone()

            if row is not None and row["status"] == "synced":
                return {
                    "event_id": body.event_id,
                    "status": "duplicate",
                    "attempts": row["attempts"],
                }

            attempts = (row["attempts"] + 1) if row is not None else 1
            now = _now()
            if row is None:
                conn.execute(
                    "INSERT INTO sync_log VALUES (?, 'pending', ?, NULL, ?, ?)",
                    (body.event_id, attempts, now, now),
                )
            else:
                conn.execute(
                    "UPDATE sync_log SET status = 'pending', attempts = ?, "
                    "updated_at = ? WHERE event_id = ?",
                    (attempts, now, body.event_id),
                )
            conn.commit()

            try:
                processor(body.payload)
            except Exception as exc:
                conn.execute(
                    "UPDATE sync_log SET status = 'failed', last_error = ?, "
                    "updated_at = ? WHERE event_id = ?",
                    (str(exc), _now(), body.event_id),
                )
                conn.commit()
                raise HTTPException(
                    status_code=502,
                    detail={
                        "event_id": body.event_id,
                        "status": "failed",
                        "attempts": attempts,
                        "error": str(exc),
                    },
                )

            conn.execute(
                "UPDATE sync_log SET status = 'synced', last_error = NULL, "
                "updated_at = ? WHERE event_id = ?",
                (_now(), body.event_id),
            )
            conn.commit()
            return {
                "event_id": body.event_id,
                "status": "synced",
                "attempts": attempts,
            }
        finally:
            conn.close()

    @app.get("/sync-log")
    def sync_log() -> list[dict]:
        conn = connect()
        try:
            rows = conn.execute(
                "SELECT event_id, status, attempts, last_error, created_at, "
                "updated_at FROM sync_log ORDER BY created_at"
            ).fetchall()
            return [dict(row) for row in rows]
        finally:
            conn.close()

    return app


app = create_app(os.environ.get("WEBHOOK_DB", "sync.db"))
