"""Blinkerbot booking connector - Python (FastAPI) example.

You only change the four functions in "YOUR FUNCTIONS" below (plus the
optional get_booking). Everything under "CONNECTOR" implements the Blinkerbot
contract: Standard Webhooks signature check, idempotency in the same
transaction as your booking, error codes, test:true (rolled back),
replaces_booking_id and the pairing code command.

    python -m venv .venv && .venv/bin/pip install -r requirements.txt
    python main.py pair blk_pair_XXXX --url https://your-site.example/blinkerbot
    uvicorn main:app --port 8000          # endpoint: POST /blinkerbot

This demo keeps its data in SQLite. With your own database open one
transaction per request on one connection and pass it as `tx` to
create_booking/cancel_booking.
"""

from __future__ import annotations

import base64
import hashlib
import hmac
import json
import os
import random
import re
import secrets
import sqlite3
import sys
import threading
import time
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
from zoneinfo import ZoneInfo

PACKAGE_VERSION = "1.0.0"
HERE = Path(__file__).resolve().parent
CONFIG = {
    "path": os.environ.get("BLINKERBOT_PATH", "/blinkerbot"),
    "db_file": os.environ.get("BOOKING_DB", str(HERE / "demo.sqlite")),
    # Pairing writes the secret here (mode 0600). Keep it out of version control.
    "secret_file": os.environ.get("BLINKERBOT_SECRET_FILE", str(HERE / ".blinkerbot-secret.json")),
    "api_base": os.environ.get("BLINKERBOT_API_BASE", "https://api.blinkerbot.com"),
    "timezone": os.environ.get("BUSINESS_TIMEZONE", "Europe/Istanbul"),
    "lock_timeout_seconds": 3.0,
}
TZ = ZoneInfo(CONFIG["timezone"])

# ============================================================ demo data (replace with your tables)

db = sqlite3.connect(CONFIG["db_file"], check_same_thread=False, isolation_level=None)
db.row_factory = sqlite3.Row
db.executescript(
    """
    CREATE TABLE IF NOT EXISTS demo_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, duration_minutes INTEGER NOT NULL, price INTEGER);
    CREATE TABLE IF NOT EXISTS demo_staff (id TEXT PRIMARY KEY, name TEXT NOT NULL);
    CREATE TABLE IF NOT EXISTS demo_service_staff (service_id TEXT NOT NULL, staff_id TEXT NOT NULL, PRIMARY KEY (service_id, staff_id));
    CREATE TABLE IF NOT EXISTS demo_bookings (
      id TEXT PRIMARY KEY, service_id TEXT NOT NULL, staff_id TEXT NOT NULL,
      start_ts INTEGER NOT NULL, end_ts INTEGER NOT NULL,
      customer_name TEXT NOT NULL, customer_phone TEXT NOT NULL, customer_email TEXT,
      channel TEXT, note TEXT, status TEXT NOT NULL
    );
    CREATE TABLE IF NOT EXISTS blinkerbot_idempotency (
      key TEXT PRIMARY KEY, request_hash TEXT NOT NULL, response_json TEXT NOT NULL,
      status TEXT NOT NULL, created_at INTEGER NOT NULL
    );
    """
)
if db.execute("SELECT COUNT(*) FROM demo_services").fetchone()[0] == 0:
    db.executescript(
        """
        INSERT INTO demo_services VALUES ('svc_haircut', 'Saç kesimi', 30, 500), ('svc_beard', 'Sakal tıraşı', 15, 200);
        INSERT INTO demo_staff VALUES ('stf_ayse', 'Ayşe Yılmaz'), ('stf_mehmet', 'Mehmet Usta');
        INSERT INTO demo_service_staff VALUES ('svc_haircut', 'stf_ayse'), ('svc_haircut', 'stf_mehmet'), ('svc_beard', 'stf_mehmet');
        """
    )
OPEN_HOUR, CLOSE_HOUR = 9, 18


class BookingError(Exception):
    """Raise with a business code, e.g. BookingError("slot_unavailable")."""

    def __init__(self, code: str):
        super().__init__(code)
        self.code = code


# ============================================================ YOUR FUNCTIONS


def list_services() -> list[dict]:
    rows = db.execute("SELECT id, name, duration_minutes, price FROM demo_services ORDER BY id").fetchall()
    return [
        {"id": r["id"], "name": r["name"], "duration_minutes": r["duration_minutes"], "price": r["price"], "staff": _staff_of(r["id"])}
        for r in rows
    ]


def find_slots(q: dict) -> list[dict]:
    """q: service_id, staff_id?, from, to, timezone -> [{start, end, staff_id?}]"""
    service = _service(q["service_id"])
    staff = _pick_staff(service["id"], q.get("staff_id"))
    now = datetime.now(timezone.utc)
    start = max(now, _parse(q["from"]))
    end = min(_parse(q["to"]), now + timedelta(days=31))
    length = timedelta(minutes=service["duration_minutes"])
    slots: list[dict] = []
    day = start.astimezone(TZ).replace(hour=0, minute=0, second=0, microsecond=0)
    while day < end and len(slots) < q.get("limit", 500):
        t = day.replace(hour=OPEN_HOUR)
        close = day.replace(hour=CLOSE_HOUR)
        while t + length <= close:
            if t >= start and t + length <= end:
                for st in staff:
                    if not _overlaps(db, st, t, t + length):
                        slots.append({"start": t.isoformat(), "end": (t + length).isoformat(), "staff_id": st})
            t += length
        day = (day + timedelta(days=1)).replace(hour=0)
    return slots


def create_booking(tx: sqlite3.Connection, b: dict) -> dict:
    """Runs inside the connector's transaction: use tx, do not commit yourself."""
    service = _service(b["service_id"])
    start, end = _parse(b["start"]).astimezone(TZ), _parse(b["end"]).astimezone(TZ)
    if end <= start or start < start.replace(hour=OPEN_HOUR, minute=0, second=0) or end > start.replace(hour=CLOSE_HOUR, minute=0, second=0):
        raise BookingError("outside_hours")
    staff_id = next((st for st in _pick_staff(service["id"], b.get("staff_id")) if not _overlaps(tx, st, start, end)), None)
    if staff_id is None:
        raise BookingError("slot_unavailable")
    booking_id = "B" + secrets.token_hex(8)
    c = b["customer"]
    tx.execute(
        "INSERT INTO demo_bookings (id, service_id, staff_id, start_ts, end_ts, customer_name, customer_phone, customer_email, channel, note, status)"
        " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'confirmed')",
        (booking_id, service["id"], staff_id, int(start.timestamp()), int(end.timestamp()), str(c["name"])[:120], str(c["phone"])[:40], c.get("email"), b.get("channel"), b.get("note")),
    )
    return {"booking_id": booking_id, "status": "confirmed", "start": start.isoformat(), "end": end.isoformat(), "staff_id": staff_id}


def cancel_booking(tx: sqlite3.Connection, booking_id: str) -> dict:
    """Runs inside the connector's transaction. An already cancelled booking must still succeed."""
    row = tx.execute("SELECT status FROM demo_bookings WHERE id = ?", (booking_id,)).fetchone()
    if row is None:
        raise BookingError("booking_not_found")
    if row["status"] != "cancelled":
        tx.execute("UPDATE demo_bookings SET status = 'cancelled' WHERE id = ?", (booking_id,))
    return {"booking_id": booking_id, "status": "cancelled"}


def get_booking(booking_id: str) -> dict | None:
    """Optional. Return None when the booking does not exist."""
    r = db.execute("SELECT id, staff_id, start_ts, end_ts, status FROM demo_bookings WHERE id = ?", (booking_id,)).fetchone()
    if r is None:
        return None
    return {
        "booking_id": r["id"],
        "status": r["status"],
        "start": datetime.fromtimestamp(r["start_ts"], TZ).isoformat(),
        "end": datetime.fromtimestamp(r["end_ts"], TZ).isoformat(),
        "staff_id": r["staff_id"],
    }


# --- demo helpers
def _parse(s: str) -> datetime:
    d = datetime.fromisoformat(str(s).replace("Z", "+00:00"))
    return d if d.tzinfo else d.replace(tzinfo=TZ)


def _service(service_id) -> sqlite3.Row:
    s = db.execute("SELECT id, duration_minutes FROM demo_services WHERE id = ?", (str(service_id),)).fetchone()
    if s is None:
        raise BookingError("invalid_service")
    return s


def _staff_of(service_id: str) -> list[dict]:
    rows = db.execute(
        "SELECT st.id, st.name FROM demo_staff st JOIN demo_service_staff ss ON ss.staff_id = st.id WHERE ss.service_id = ? ORDER BY st.id", (service_id,)
    ).fetchall()
    return [{"id": r["id"], "name": r["name"]} for r in rows]


def _pick_staff(service_id: str, wanted) -> list[str]:
    ids = [s["id"] for s in _staff_of(service_id)]
    if wanted in (None, ""):
        return ids
    if str(wanted) not in ids:
        raise BookingError("invalid_staff")
    return [str(wanted)]


def _overlaps(conn, staff_id: str, start: datetime, end: datetime) -> bool:
    row = conn.execute(
        "SELECT COUNT(*) FROM demo_bookings WHERE staff_id = ? AND status <> 'cancelled' AND start_ts < ? AND end_ts > ?",
        (staff_id, int(end.timestamp()), int(start.timestamp())),
    ).fetchone()
    return row[0] > 0


# ============================================================ CONNECTOR (no changes needed)

BUSINESS_CODES = {
    "slot_unavailable",
    "invalid_service",
    "invalid_staff",
    "outside_hours",
    "invalid_customer",
    "booking_not_found",
    "cancellation_not_allowed",
    "idempotency_mismatch",
    "request_in_progress",
}
_lock = threading.Lock()  # one write transaction at a time on this connection


def load_secrets() -> list[str]:
    out: list[str] = []
    if os.environ.get("BLINKERBOT_SIGNING_SECRET"):
        out.append(os.environ["BLINKERBOT_SIGNING_SECRET"].strip())
    try:
        stored = json.loads(Path(CONFIG["secret_file"]).read_text("utf-8"))
        out += [s for s in stored.get("signing_secrets", []) if isinstance(s, str)]
    except (OSError, ValueError):
        pass  # not paired yet
    return list(dict.fromkeys(out))


def sign(secret: str, msg_id: str, ts: str, raw_body: bytes) -> str:
    key = base64.b64decode(secret[6:] if secret.startswith("whsec_") else secret)
    return base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.".encode() + raw_body, hashlib.sha256).digest()).decode()


def verify_signature(secret_list: list[str], msg_id: str | None, ts: str | None, header: str | None, raw_body: bytes, now: float | None = None) -> bool:
    if not msg_id or len(msg_id) > 256 or not ts or not re.fullmatch(r"\d{1,12}", ts) or not header or not secret_list:
        return False
    if abs(int(now if now is not None else time.time()) - int(ts)) > 300:
        return False
    given = [p[3:] for p in header.split() if p.startswith("v1,")]
    valid = False
    for secret in secret_list:
        try:
            expected = sign(secret, msg_id, ts, raw_body)
        except ValueError:
            continue
        for g in given:
            if hmac.compare_digest(expected.encode(), g.encode()):  # constant time
                valid = True
    return valid


def canonical_json(v) -> str:
    return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def _sha256(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def request_hash(operation: str, data) -> str:
    return _sha256(canonical_json({"data": data, "operation": operation}))


def storage_key(test: bool, account: str | None, operation: str, key: str) -> str:
    return _sha256(f"v1\n{'test' if test else 'live'}\n{account or ''}\n{operation}\n{key}")


def _transaction(test: bool, work, idem: tuple[str, str] | None = None):
    if not _lock.acquire(timeout=CONFIG["lock_timeout_seconds"]):
        raise BookingError("request_in_progress")
    try:
        if idem is not None:
            k, h = idem
            row = db.execute("SELECT request_hash, response_json, status FROM blinkerbot_idempotency WHERE key = ?", (k,)).fetchone()
            if row is not None:
                if row["request_hash"] != h:
                    raise BookingError("idempotency_mismatch")
                if row["status"] != "done":
                    raise BookingError("request_in_progress")
                return json.loads(row["response_json"])
        db.execute("BEGIN IMMEDIATE")
        try:
            result = work(db)
            if idem is not None:
                db.execute(
                    "INSERT INTO blinkerbot_idempotency (key, request_hash, response_json, status, created_at) VALUES (?, ?, ?, 'done', ?)",
                    (idem[0], idem[1], json.dumps(result), int(time.time())),
                )
            db.execute("ROLLBACK" if test else "COMMIT")
        except BaseException:
            db.execute("ROLLBACK")
            raise
        if test and idem is not None:
            # keep only the answer of a test request (no booking), so "same key -> same id" works
            db.execute(
                "INSERT OR IGNORE INTO blinkerbot_idempotency (key, request_hash, response_json, status, created_at) VALUES (?, ?, ?, 'done', ?)",
                (idem[0], idem[1], json.dumps(result), int(time.time())),
            )
        if random.random() < 0.02:
            db.execute("DELETE FROM blinkerbot_idempotency WHERE created_at < ?", (int(time.time()) - 30 * 86400,))
        return result
    finally:
        _lock.release()


def _non_empty(v) -> bool:
    return isinstance(v, str) and v != ""


# Not a business code: an optional operation that is not supported here.
# Always HTTP 200 - Blinkerbot treats every 5xx (501 included) as "unreachable".
def _not_implemented() -> tuple[int, dict]:
    return 200, {"ok": False, "error": {"code": "not_implemented", "message": "not implemented"}}


# find_slots: earliest `limit` slots (contract maximum 500) and well under the
# 64 KB answer limit Blinkerbot enforces.
MAX_BODY_BYTES = 65536
MAX_SLOTS = 500
MAX_SLOTS_JSON_BYTES = 60000


def _slot_time(slot) -> float:
    try:
        return datetime.fromisoformat(str(slot.get("start")).replace("Z", "+00:00")).timestamp()
    except (AttributeError, TypeError, ValueError):
        return float("inf")


def limit_slots(slots, limit: int) -> list:
    ordered = sorted(slots or [], key=_slot_time)  # stable: equal starts keep their order
    out, size = [], 2
    for slot in ordered:
        if len(out) >= limit:
            break
        size += len(json.dumps(slot, ensure_ascii=False).encode("utf-8")) + 1
        if size > MAX_SLOTS_JSON_BYTES:
            break
        out.append(slot)
    return out


def _normalize_booking(b: dict, request: dict, allow_cancelled: bool) -> dict:
    if not b or b.get("booking_id") in (None, ""):
        raise RuntimeError("booking result needs booking_id")
    status = b.get("status", "confirmed")
    if status not in (("confirmed", "pending", "cancelled") if allow_cancelled else ("confirmed", "pending")):
        raise RuntimeError("invalid booking status")
    out = {"booking_id": str(b["booking_id"]), "status": status, "start": b.get("start", request.get("start")), "end": b.get("end", request.get("end"))}
    staff = b.get("staff_id", request.get("staff_id"))
    if staff not in (None, ""):
        out["staff_id"] = str(staff)
    return out


def handle(headers: dict, raw_body: bytes) -> tuple[int, dict]:
    """Returns (http_status, payload). Synchronous: run it in a worker thread."""
    if len(raw_body) > MAX_BODY_BYTES:
        return 413, {"ok": False, "error": {"code": "payload_too_large"}}
    if not verify_signature(load_secrets(), headers.get("webhook-id"), headers.get("webhook-timestamp"), headers.get("webhook-signature"), raw_body):
        return 401, {"ok": False, "error": {"code": "unauthorized"}}
    bad = (400, {"ok": False, "error": {"code": "bad_request"}})
    try:
        req = json.loads(raw_body.decode("utf-8"))
    except (ValueError, UnicodeDecodeError):
        return bad
    if not isinstance(req, dict) or not isinstance(req.get("operation"), str):
        return bad
    data = req.get("data") or {}
    if not isinstance(data, dict):
        return bad
    key = req.get("idempotency_key") if _non_empty(req.get("idempotency_key")) and len(req["idempotency_key"]) <= 255 else None
    account = req.get("account") if _non_empty(req.get("account")) else None
    test = req.get("test") is True
    op = req["operation"]

    def ok(d):
        return 200, {"ok": True, "data": d}

    try:
        if op == "ping":
            # replaces_booking_id is handled below in one transaction (cancel old + create new)
            return ok({"pong": True, "package": "python", "package_version": PACKAGE_VERSION, "contract_version": 1, "capabilities": ["replaces_booking_id"]})
        if op == "list_services":
            return ok({"services": list_services()})
        if op == "find_slots":
            if not (_non_empty(data.get("service_id")) and _non_empty(data.get("from")) and _non_empty(data.get("to"))):
                return bad
            raw_limit = data.get("limit")
            if raw_limit is not None and (isinstance(raw_limit, bool) or not isinstance(raw_limit, int) or raw_limit < 1):
                return bad
            limit = min(raw_limit if raw_limit is not None else MAX_SLOTS, MAX_SLOTS)
            return ok({"slots": limit_slots(find_slots({"timezone": CONFIG["timezone"], **data, "limit": limit}), limit)})
        if op == "get_booking":
            getter = globals().get("get_booking")
            if getter is None:
                return _not_implemented()
            if not _non_empty(data.get("booking_id")):
                return bad
            b = getter(data["booking_id"])
            if b is None:
                raise BookingError("booking_not_found")
            return ok(_normalize_booking(b, {}, True))
        if op == "create_booking":
            if key is None or not all(_non_empty(data.get(f)) for f in ("service_id", "start", "end")):
                return bad
            customer = data.get("customer")
            if not isinstance(customer, dict) or not _non_empty(customer.get("name")) or not _non_empty(customer.get("phone")):
                raise BookingError("invalid_customer")
            replaces = data.get("replaces_booking_id") if _non_empty(data.get("replaces_booking_id")) else None

            def work(tx):
                replaced = False
                if replaces:
                    try:
                        cancel_booking(tx, replaces)  # old one first, so the new one may overlap it
                        replaced = True
                    except BookingError as e:
                        if e.code != "booking_not_found":
                            raise
                result = _normalize_booking(create_booking(tx, {k: v for k, v in data.items() if k != "replaces_booking_id"}), data, False)
                if replaces:
                    result["replaced"] = replaced
                return result

            return ok(_transaction(test, work, (storage_key(test, account, op, key), request_hash(op, data))))
        if op == "cancel_booking":
            if not _non_empty(data.get("booking_id")):
                return bad

            def work_cancel(tx):
                r = cancel_booking(tx, data["booking_id"]) or {}
                return {"booking_id": str(r.get("booking_id", data["booking_id"])), "status": "cancelled"}

            idem = (storage_key(test, account, op, key), request_hash(op, data)) if key else None
            return ok(_transaction(test, work_cancel, idem))
        return _not_implemented()
    except BookingError as e:
        if e.code in BUSINESS_CODES:
            return 200, {"ok": False, "error": {"code": e.code, "message": e.code}}
        return 500, {"ok": False, "error": {"code": "internal_error"}}
    except Exception as e:  # noqa: BLE001 - never leak details
        print(f"blinkerbot: {type(e).__name__} in {op}", file=sys.stderr)
        return 500, {"ok": False, "error": {"code": "internal_error"}}


# ---------------------------------------------------------------- pairing


def pair(code: str, endpoint_url: str, account: str | None = None) -> str:
    c = code.strip()
    if c.startswith("blk_pair_"):
        c = "blk_pair_" + re.sub(r"[\s-]+", "", c[9:])
    if not re.fullmatch(r"blk_pair_[A-Za-z2-7]{26}", c):
        raise ValueError("pairing code must look like blk_pair_ followed by 26 characters")
    # http only with the same test switch as the api base: Blinkerbot itself calls https endpoints only.
    insecure = os.environ.get("BLINKERBOT_ALLOW_INSECURE_API") == "1"
    if not re.match(r"^https?://[^/@\s]+" if insecure else r"^https://[^/@\s]+", endpoint_url, re.IGNORECASE):
        raise ValueError("endpoint URL must be a full https:// address")
    base = CONFIG["api_base"].rstrip("/")
    if not base.startswith("https://") and not insecure:
        raise ValueError("api base must use https")
    body = json.dumps(
        {"code": c, "endpoint_url": endpoint_url, "package_kind": "python", "package_version": PACKAGE_VERSION, "account": account}
    ).encode()
    request = urllib.request.Request(f"{base}/public/v1/pair", data=body, method="POST", headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(request, timeout=20) as res:  # noqa: S310 - fixed https base
            payload = json.loads(res.read(65536).decode("utf-8"))
    except (urllib.error.URLError, ValueError) as e:
        raise RuntimeError("pairing_failed") from e
    secret = (payload.get("data") or {}).get("signing_secret") if payload.get("ok") is True else None
    if not isinstance(secret, str) or not re.fullmatch(r"whsec_[A-Za-z0-9+/]{40,}={0,2}", secret):
        raise RuntimeError("pairing_failed")
    path = Path(CONFIG["secret_file"])
    tmp = path.with_name(path.name + "." + secrets.token_hex(4) + ".tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump({"signing_secrets": [secret], "workspace_name": payload["data"].get("workspace_name", ""), "paired_at": datetime.now(timezone.utc).isoformat()}, f)
    os.replace(tmp, path)
    return str(payload["data"].get("workspace_name", ""))


# ---------------------------------------------------------------- web app

try:
    from fastapi import FastAPI, Request, Response
    from fastapi.concurrency import run_in_threadpool

    app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)

    @app.api_route(CONFIG["path"], methods=["GET", "PUT", "PATCH", "DELETE"])
    async def not_allowed() -> Response:
        return Response('{"ok":false,"error":{"code":"method_not_allowed"}}', status_code=405, media_type="application/json", headers={"Allow": "POST"})

    def _too_large() -> Response:
        return Response('{"ok":false,"error":{"code":"payload_too_large"}}', status_code=413, media_type="application/json", headers={"Cache-Control": "no-store"})

    @app.post(CONFIG["path"])
    async def blinkerbot_endpoint(request: Request) -> Response:
        # Exact bytes, before any parsing, and never more than 64 KB in memory.
        declared = request.headers.get("content-length")
        if declared is not None and (not declared.isdigit() or int(declared) > MAX_BODY_BYTES):
            return _too_large()
        chunks, size = [], 0
        async for chunk in request.stream():
            size += len(chunk)
            if size > MAX_BODY_BYTES:
                return _too_large()
            chunks.append(chunk)
        raw = b"".join(chunks)
        headers = {k: request.headers.get(k) for k in ("webhook-id", "webhook-timestamp", "webhook-signature")}
        status, payload = await run_in_threadpool(handle, headers, raw)
        return Response(json.dumps(payload, ensure_ascii=False), status_code=status, media_type="application/json", headers={"Cache-Control": "no-store"})

except ImportError:  # pairing CLI works without FastAPI installed
    app = None


if __name__ == "__main__":
    args = sys.argv[1:]
    if args[:1] == ["pair"] and len(args) >= 2 and "--url" in args:
        url = args[args.index("--url") + 1]
        acct = args[args.index("--account") + 1] if "--account" in args else None
        try:
            ws = pair(args[1], url, acct)
        except (ValueError, RuntimeError) as e:
            print(f"error: {e}", file=sys.stderr)
            sys.exit(1)
        print(f'Paired with Blinkerbot workspace "{ws}". The signing secret was saved to {CONFIG["secret_file"]} (not shown).')
        sys.exit(0)
    print("usage: python main.py pair <blk_pair_code> --url <https://your-site/blinkerbot> [--account <id>]\n       uvicorn main:app --port 8000")
    sys.exit(2)
