"""
ABOS Auth – WhatsApp login service
==================================
Client systems (such as the allBETs main site) can verify a WhatsApp number in two ways.

1. One-time code (needs an approved Authentication template): POST /v1/otp/send with a phone number and later
   POST /v1/otp/verify with the code the person typed. Codes are random, single-use, stored only as a keyed
   hash and expire after AUTH_OTP_TTL_SECONDS.
2. Message link, no template and no code: POST /v1/link/start returns a wa.me link carrying a one-time token. The
   person sends that message from their WhatsApp; the Aggie API (which receives Meta's signed webhook) tells this
   service who sent it through /admin/link/inbound, and the client reads the verified number with
   GET /v1/link/status/{session_id}. WhatsApp itself vouches for the sender's number.

The Aggie API manages the service through /admin (X-Admin-Key).
"""

from __future__ import annotations

import ipaddress
import logging
import math
import re
import secrets
import time
import uuid
from urllib.parse import quote
from contextlib import asynccontextmanager
from datetime import datetime, timezone

from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException

from app.config import Settings
from app.db import Database
from app.security import (
    Vault, hash_secret, mask_phone, new_client_key, normalize_phone, same, split_client_key,
)
from app.whatsapp import DeliveryError, GraphSender, Sender, WhatsAppConfig

logger = logging.getLogger("abos.auth")

_TOKEN = re.compile(r"^[A-Za-z0-9_.|\-]{20,600}$")
_PHONE_NUMBER_ID = re.compile(r"^\d{12,20}$")
_TEMPLATE = re.compile(r"^[a-z0-9_]{1,512}$")
_LANGUAGE = re.compile(r"^[a-z]{2,3}(_[A-Z]{2})?$")
# One-time link tokens: BET- plus 8 characters without look-alikes (no I, O, 0 or 1).
_TOKEN_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
_LINK_TOKEN = re.compile(r"BET-[A-HJ-NP-Z2-9]{8}")
_WA_ID = re.compile(r"^\d{8,15}$")


class ApiError(Exception):
    def __init__(self, status: int, error: str, message: str, retry_after: int | None = None) -> None:
        self.status, self.error, self.message, self.retry_after = status, error, message, retry_after


class SendBody(BaseModel):
    phone: str = Field(min_length=7, max_length=32)
    purpose: str | None = Field(default=None, max_length=40, pattern=r"^[A-Za-z0-9_.:-]*$")


class VerifyBody(BaseModel):
    request_id: str = Field(min_length=8, max_length=64)
    code: str = Field(min_length=4, max_length=10, pattern=r"^\d+$")


class WhatsAppBody(BaseModel):
    phone_number_id: str | None = None
    access_token: str | None = None
    template_name: str | None = None
    template_language: str | None = None
    include_button: bool | None = None
    clear_token: bool = False


class LinkStartBody(BaseModel):
    # When given, only this number can complete the login (the client already knows whom it is signing in).
    phone: str | None = Field(default=None, min_length=7, max_length=32)
    purpose: str | None = Field(default=None, max_length=40, pattern=r"^[A-Za-z0-9_.:-]*$")


class LinkInboundBody(BaseModel):
    phone_number_id: str = Field(min_length=1, max_length=40)
    from_wa_id: str = Field(min_length=1, max_length=40)
    text: str = Field(default="", max_length=4096)
    wa_message_id: str | None = Field(default=None, max_length=200)


class ClientBody(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    rate_per_minute: int | None = Field(default=None, ge=1, le=1000)
    allowed_country_codes: list[str] = Field(default_factory=list, max_length=50)
    allowed_ips: list[str] = Field(default_factory=list, max_length=50)


def _iso(ts: float | None) -> str | None:
    return None if ts is None else datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()


def create_app(settings: Settings | None = None, sender: Sender | None = None, clock=time.time) -> FastAPI:
    settings = settings or Settings()
    db = Database(settings.db_path)
    vault = Vault(settings.master_key) if settings.master_key_ok else None
    sender = sender or GraphSender(settings.graph_base, settings.send_timeout_seconds)

    @asynccontextmanager
    async def lifespan(_: FastAPI):
        yield
        db.close()

    app = FastAPI(title=settings.app_name, version=settings.app_version, lifespan=lifespan)
    app.state.db = db

    # ---- housekeeping -------------------------------------------------------------------------------------
    now0 = clock()
    with db.tx() as c:
        c.execute("DELETE FROM events WHERE ts < ?", (now0 - settings.event_retention_days * 86400,))
        c.execute("DELETE FROM otp_requests WHERE created_at < ?", (now0 - settings.request_retention_days * 86400,))
        c.execute("DELETE FROM link_logins WHERE created_at < ?", (now0 - settings.link_retention_days * 86400,))
        c.execute("DELETE FROM rate_hits WHERE ts < ?", (now0 - 86400,))

    # ---- errors ------------------------------------------------------------------------------------------
    @app.exception_handler(ApiError)
    async def _api_error(_: Request, exc: ApiError) -> JSONResponse:
        headers = {"Retry-After": str(exc.retry_after)} if exc.retry_after else None
        body = {"error": exc.error, "message": exc.message}
        if exc.retry_after:
            body["retry_after"] = exc.retry_after
        return JSONResponse(body, status_code=exc.status, headers=headers)

    @app.exception_handler(RequestValidationError)
    async def _invalid(_: Request, exc: RequestValidationError) -> JSONResponse:
        first = exc.errors()[0] if exc.errors() else {}
        where = ".".join(str(p) for p in first.get("loc", []) if p != "body")
        return JSONResponse({"error": "invalid_request", "message": f"{where}: {first.get('msg', 'invalid')}".strip(": ")},
                            status_code=422)

    @app.exception_handler(StarletteHTTPException)
    async def _http(_: Request, exc: StarletteHTTPException) -> JSONResponse:
        return JSONResponse({"error": f"http_{exc.status_code}", "message": str(exc.detail)}, status_code=exc.status_code)

    # ---- helpers -----------------------------------------------------------------------------------------
    def event(conn, client_id, request_id, phone, name, detail=None) -> None:
        conn.execute(
            "INSERT INTO events(ts, client_id, request_id, phone, event, detail) VALUES (?,?,?,?,?,?)",
            (clock(), client_id, request_id, mask_phone(phone) if phone else None, name, detail),
        )

    def get_setting(conn, key: str) -> str | None:
        row = conn.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
        return row["value"] if row else None

    def put_setting(conn, key: str, value: str) -> None:
        conn.execute("INSERT INTO settings(key, value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
                     (key, value))

    def wa_parts() -> dict:
        with db.tx() as c:
            token_enc = get_setting(c, "wa.token_enc")
            token = vault.decrypt(token_enc) if (vault and token_enc) else None
            return {
                "phone_number_id": get_setting(c, "wa.phone_number_id") or "",
                "access_token": token or "",
                "token_hint": get_setting(c, "wa.token_hint") or "",
                "token_unreadable": bool(token_enc) and token is None,
                "template_name": get_setting(c, "wa.template_name") or "",
                "template_language": get_setting(c, "wa.template_language") or "en_US",
                "include_button": (get_setting(c, "wa.include_button") or "1") == "1",
            }

    def wa_config() -> WhatsAppConfig | None:
        p = wa_parts()
        if not (p["phone_number_id"] and p["access_token"] and p["template_name"]):
            return None
        return WhatsAppConfig(p["phone_number_id"], p["access_token"], p["template_name"],
                              p["template_language"], p["include_button"])

    def wa_base() -> WhatsAppConfig | None:
        """Number and token only: plain messages do not need a template."""
        p = wa_parts()
        if not (p["phone_number_id"] and p["access_token"]):
            return None
        return WhatsAppConfig(p["phone_number_id"], p["access_token"], p["template_name"],
                              p["template_language"], p["include_button"])

    def client_ip(request: Request) -> str:
        if settings.trust_proxy:
            forwarded = request.headers.get("x-forwarded-for")
            if forwarded:
                return forwarded.split(",")[-1].strip()
        return request.client.host if request.client else ""

    async def current_client(request: Request):
        presented = request.headers.get("x-api-key", "").strip()
        auth = request.headers.get("authorization", "")
        if not presented and auth.lower().startswith("bearer "):
            presented = auth[7:].strip()
        parts = split_client_key(presented)
        if not parts:
            raise ApiError(401, "unauthorized", "A valid API key is required (Authorization: Bearer wak_...)")
        key_id, secret = parts
        now = clock()
        problem: ApiError | None = None
        with db.tx() as c:
            row = c.execute("SELECT * FROM clients WHERE key_id=?", (key_id,)).fetchone()
            if row is None or not row["active"] or not same(hash_secret(secret), row["key_hash"]):
                problem = ApiError(401, "unauthorized", "A valid API key is required")
            elif row["allowed_ips"] and client_ip(request) not in row["allowed_ips"].split(","):
                event(c, row["id"], None, None, "ip_refused", client_ip(request))
                problem = ApiError(403, "ip_not_allowed", "This API key cannot be used from this address")
            else:
                c.execute("DELETE FROM rate_hits WHERE client_id=? AND ts < ?", (row["id"], now - 60))
                used = c.execute("SELECT COUNT(*) FROM rate_hits WHERE client_id=?", (row["id"],)).fetchone()[0]
                if used >= row["rate_per_minute"]:
                    event(c, row["id"], None, None, "rate_limited", f"{row['rate_per_minute']}/min")
                    problem = ApiError(429, "rate_limited", "Too many requests for this API key", retry_after=60)
                else:
                    c.execute("INSERT INTO rate_hits(client_id, ts) VALUES (?,?)", (row["id"], now))
                    c.execute("UPDATE clients SET last_used_at=? WHERE id=?", (now, row["id"]))
        if problem:
            raise problem
        return row

    async def admin(request: Request) -> None:
        if not settings.admin_key_ok:
            raise ApiError(503, "admin_disabled", "AUTH_ADMIN_KEY is not set (32+ characters) on the server")
        if not same(request.headers.get("x-admin-key", ""), settings.admin_key):
            raise ApiError(401, "unauthorized", "Admin key required")

    # ---- public --------------------------------------------------------------------------------------------
    @app.get("/health")
    async def health() -> dict:
        return {"status": "ok", "service": settings.app_name, "version": settings.app_version}

    @app.post("/v1/otp/send")
    async def send_otp(body: SendBody, client=Depends(current_client)) -> dict:
        if vault is None:
            raise ApiError(503, "not_configured", "The service is not set up yet")
        cfg = wa_config()
        if cfg is None:
            raise ApiError(503, "not_configured", "WhatsApp sending is not set up yet")
        try:
            phone = normalize_phone(body.phone)
        except ValueError as exc:
            raise ApiError(422, "invalid_phone", str(exc)) from exc
        prefixes = [p for p in client["allowed_country_codes"].split(",") if p]
        if prefixes and not any(phone[1:].startswith(p) for p in prefixes):
            raise ApiError(403, "country_not_allowed", "This API key may not send codes to that country")

        now = clock()
        request_id = uuid.uuid4().hex
        digits = settings.otp_length
        code = f"{secrets.randbelow(10 ** digits):0{digits}d}"
        problem: ApiError | None = None
        with db.tx() as c:
            last = c.execute(
                "SELECT created_at FROM otp_requests WHERE phone=? AND client_id=? AND status!='failed_send' "
                "ORDER BY created_at DESC LIMIT 1", (phone, client["id"])).fetchone()
            recent = c.execute("SELECT COUNT(*) FROM otp_requests WHERE phone=? AND created_at>?",
                               (phone, now - 3600)).fetchone()[0]
            if last and now - last["created_at"] < settings.resend_cooldown_seconds:
                wait = math.ceil(settings.resend_cooldown_seconds - (now - last["created_at"]))
                event(c, client["id"], None, phone, "resend_too_soon")
                problem = ApiError(429, "resend_too_soon", "Wait before asking for another code", retry_after=wait)
            elif recent >= settings.max_sends_per_phone_per_hour:
                event(c, client["id"], None, phone, "phone_limit")
                problem = ApiError(429, "too_many_codes", "Too many codes were requested for this number", retry_after=3600)
            else:
                c.execute("UPDATE otp_requests SET status='superseded' WHERE phone=? AND client_id=? AND status='pending'",
                          (phone, client["id"]))
                c.execute(
                    "INSERT INTO otp_requests(id, client_id, phone, purpose, code_hash, created_at, expires_at, status) "
                    "VALUES (?,?,?,?,?,?,?,'pending')",
                    (request_id, client["id"], phone, body.purpose, vault.code_hash(request_id, code), now,
                     now + settings.otp_ttl_seconds))
        if problem:
            raise problem

        try:
            message_id = await sender.send_otp(cfg, phone, code)
        except DeliveryError as exc:
            with db.tx() as c:
                c.execute("UPDATE otp_requests SET status='failed_send' WHERE id=?", (request_id,))
                event(c, client["id"], request_id, phone, "send_failed", str(exc)[:300])
            logger.warning("WhatsApp delivery failed for %s: %s", mask_phone(phone), exc)
            raise ApiError(502, "delivery_failed", "The code could not be delivered by WhatsApp") from exc
        with db.tx() as c:
            c.execute("UPDATE otp_requests SET wa_message_id=? WHERE id=?", (message_id, request_id))
            event(c, client["id"], request_id, phone, "sent", body.purpose)
        return {"request_id": request_id, "expires_in": settings.otp_ttl_seconds,
                "resend_after": settings.resend_cooldown_seconds}

    @app.post("/v1/otp/verify")
    async def verify_otp(body: VerifyBody, client=Depends(current_client)) -> dict:
        if vault is None:
            raise ApiError(503, "not_configured", "The service is not set up yet")
        now = clock()
        with db.tx() as c:
            row = c.execute("SELECT * FROM otp_requests WHERE id=? AND client_id=?",
                            (body.request_id, client["id"])).fetchone()
            if row is None:
                return {"valid": False, "reason": "unknown_request"}
            rid, phone = row["id"], row["phone"]
            if row["status"] == "verified":
                return {"valid": False, "reason": "already_used"}
            if row["status"] in ("superseded", "failed_send"):
                return {"valid": False, "reason": "replaced" if row["status"] == "superseded" else "not_delivered"}
            if row["status"] == "locked":
                return {"valid": False, "reason": "too_many_attempts", "attempts_left": 0}
            if row["status"] == "expired" or now > row["expires_at"]:
                c.execute("UPDATE otp_requests SET status='expired' WHERE id=?", (rid,))
                event(c, client["id"], rid, phone, "expired")
                return {"valid": False, "reason": "expired"}
            attempts = row["attempts"] + 1
            if same(vault.code_hash(rid, body.code), row["code_hash"]):
                c.execute("UPDATE otp_requests SET status='verified', attempts=? WHERE id=?", (attempts, rid))
                event(c, client["id"], rid, phone, "verified")
                return {"valid": True}
            left = max(settings.otp_max_attempts - attempts, 0)
            status = "locked" if left == 0 else "pending"
            c.execute("UPDATE otp_requests SET attempts=?, status=? WHERE id=?", (attempts, status, rid))
            event(c, client["id"], rid, phone, "wrong_code" if left else "locked", f"attempt {attempts}")
            return {"valid": False, "reason": "invalid_code", "attempts_left": left}


    # ---- message link login (no template, no code) ------------------------------------------------------------------
    @app.post("/v1/link/start")
    async def link_start(body: LinkStartBody, client=Depends(current_client)) -> dict:
        if vault is None:
            raise ApiError(503, "not_configured", "The service is not set up yet")
        cfg = wa_base()
        if cfg is None:
            raise ApiError(503, "not_configured", "WhatsApp is not set up yet")
        expected = None
        if body.phone:
            try:
                expected = normalize_phone(body.phone)
            except ValueError as exc:
                raise ApiError(422, "invalid_phone", str(exc)) from exc
            prefixes = [p for p in client["allowed_country_codes"].split(",") if p]
            if prefixes and not any(expected[1:].startswith(p) for p in prefixes):
                raise ApiError(403, "country_not_allowed", "This API key may not log in numbers from that country")

        with db.tx() as c:
            shown = get_setting(c, "wa.display_phone")
        if not shown:
            try:
                info = await sender.check(cfg)
            except DeliveryError as exc:
                logger.warning("Could not read the WhatsApp number from Meta: %s", exc)
                raise ApiError(502, "whatsapp_unreachable", "WhatsApp could not be reached to read the sending number") from exc
            shown = re.sub(r"\D", "", str(info.get("display_phone_number") or ""))
            if not _WA_ID.match(shown):
                raise ApiError(502, "whatsapp_unreachable", "WhatsApp did not report the sending number")
            with db.tx() as c:
                put_setting(c, "wa.display_phone", shown)

        now = clock()
        session_id = uuid.uuid4().hex
        token = "BET-" + "".join(secrets.choice(_TOKEN_ALPHABET) for _ in range(8))
        with db.tx() as c:
            c.execute(
                "INSERT INTO link_logins(id, client_id, token_hash, expected_phone, purpose, created_at, expires_at, status) "
                "VALUES (?,?,?,?,?,?,?,'pending')",
                (session_id, client["id"], vault.code_hash("link", token), expected, body.purpose, now,
                 now + settings.link_ttl_seconds))
            event(c, client["id"], session_id, expected, "link_started", body.purpose)
        text = f"Log in to {client['name']}: {token}"
        return {
            "session_id": session_id,
            "token": token,
            "text": text,
            "whatsapp_number": "+" + shown,
            "link": f"https://wa.me/{shown}?text={quote(text, safe='')}",
            "expires_in": settings.link_ttl_seconds,
        }

    @app.get("/v1/link/status/{session_id}")
    async def link_status(session_id: str, client=Depends(current_client)) -> dict:
        now = clock()
        with db.tx() as c:
            row = c.execute("SELECT * FROM link_logins WHERE id=? AND client_id=?", (session_id, client["id"])).fetchone()
            if row is None:
                raise ApiError(404, "not_found", "No such login session")
            status = row["status"]
            if status == "pending" and now > row["expires_at"]:
                c.execute("UPDATE link_logins SET status='expired' WHERE id=?", (session_id,))
                event(c, client["id"], session_id, row["expected_phone"], "link_expired")
                return {"status": "expired"}
            if status == "verified":
                # the verified number is handed over once; asking again is refused so it cannot be replayed
                c.execute("UPDATE link_logins SET status='consumed' WHERE id=?", (session_id,))
                event(c, client["id"], session_id, row["verified_phone"], "link_consumed")
                return {"status": "verified", "phone": row["verified_phone"], "verified_at": _iso(row["verified_at"])}
            return {"status": status}

    @app.post("/admin/link/inbound", dependencies=[Depends(admin)])
    async def admin_link_inbound(body: LinkInboundBody) -> dict:
        """Called by the Aggie API for every signed inbound WhatsApp message; says whether it completed a login."""
        if vault is None:
            return {"matched": False, "reason": "not_configured"}
        cfg = wa_base()
        if cfg is None or body.phone_number_id != cfg.phone_number_id:
            return {"matched": False, "reason": "other_number"}
        wa_id = re.sub(r"\D", "", body.from_wa_id)
        if not _WA_ID.match(wa_id):
            return {"matched": False, "reason": "bad_sender"}
        sender_phone = "+" + wa_id
        now = clock()
        reply = None
        result: dict = {"matched": False}
        for token in dict.fromkeys(_LINK_TOKEN.findall((body.text or "").upper())):
            with db.tx() as c:
                row = c.execute("SELECT * FROM link_logins WHERE token_hash=?", (vault.code_hash("link", token),)).fetchone()
                if row is None:
                    continue
                if row["status"] != "pending" or now > row["expires_at"]:
                    if row["status"] == "pending":
                        c.execute("UPDATE link_logins SET status='expired' WHERE id=?", (row["id"],))
                    result = {"matched": True, "status": "expired"}
                    reply = "This login link has expired or was already used. Please start the login again."
                elif row["expected_phone"] and row["expected_phone"] != sender_phone:
                    c.execute("UPDATE link_logins SET status='rejected' WHERE id=?", (row["id"],))
                    event(c, row["client_id"], row["id"], sender_phone, "link_rejected", "number mismatch")
                    result = {"matched": True, "status": "rejected"}
                    reply = "This number does not match the one used to log in. Please start the login again."
                else:
                    c.execute("UPDATE link_logins SET status='verified', verified_phone=?, verified_at=? WHERE id=?",
                              (sender_phone, now, row["id"]))
                    event(c, row["client_id"], row["id"], sender_phone, "link_verified", body.wa_message_id)
                    result = {"matched": True, "status": "verified"}
                    reply = "You are verified. Go back to the app to continue."
            break
        if reply:
            try:
                await sender.send_text(cfg, sender_phone, reply)
            except DeliveryError as exc:
                logger.warning("Could not send the login confirmation to %s: %s", mask_phone(sender_phone), exc)
        return result

    # ---- admin (called by the Aggie API) ------------------------------------------------------------------------
    @app.get("/admin/status", dependencies=[Depends(admin)])
    async def admin_status() -> dict:
        p = wa_parts()
        since = clock() - 86400
        with db.tx() as c:
            counts = {r["event"]: r["n"] for r in c.execute(
                "SELECT event, COUNT(*) n FROM events WHERE ts>? GROUP BY event", (since,))}
            active = c.execute("SELECT COUNT(*) FROM clients WHERE active=1").fetchone()[0]
        return {
            "configured": bool(vault and p["phone_number_id"] and p["access_token"] and p["template_name"]),
            "master_key_set": vault is not None,
            "phone_number_id": p["phone_number_id"] or None,
            "token_saved": bool(p["access_token"]),
            "token_unreadable": p["token_unreadable"],
            "token_hint": p["token_hint"] or None,
            "template_name": p["template_name"] or None,
            "template_language": p["template_language"],
            "include_button": p["include_button"],
            "otp_length": settings.otp_length,
            "otp_ttl_seconds": settings.otp_ttl_seconds,
            "otp_max_attempts": settings.otp_max_attempts,
            "active_clients": active,
            "last_24h": {"sent": counts.get("sent", 0), "verified": counts.get("verified", 0),
                         "failed": counts.get("send_failed", 0)},
        }

    @app.put("/admin/whatsapp", dependencies=[Depends(admin)])
    async def admin_save_whatsapp(body: WhatsAppBody) -> dict:
        updates: dict[str, str] = {}
        if body.phone_number_id is not None:
            value = re.sub(r"\s+", "", body.phone_number_id)
            if not _PHONE_NUMBER_ID.match(value):
                raise ApiError(400, "invalid_phone_number_id",
                               "That is not a Phone Number ID — it is the long number (12+ digits) on Meta's WhatsApp API Setup page, not the phone number")
            updates["wa.phone_number_id"] = value
        if body.template_name is not None:
            if not _TEMPLATE.match(body.template_name.strip()):
                raise ApiError(400, "invalid_template_name", "Template names use lowercase letters, digits and underscores")
            updates["wa.template_name"] = body.template_name.strip()
        if body.template_language is not None:
            if not _LANGUAGE.match(body.template_language.strip()):
                raise ApiError(400, "invalid_template_language", "Use a code such as en_US")
            updates["wa.template_language"] = body.template_language.strip()
        if body.include_button is not None:
            updates["wa.include_button"] = "1" if body.include_button else "0"
        if body.access_token is not None:
            if vault is None:
                raise ApiError(503, "master_key_missing", "AUTH_MASTER_KEY (32+ characters) is not set on the server")
            token = re.sub(r"\s+", "", body.access_token)
            if not _TOKEN.match(token):
                raise ApiError(400, "invalid_token", "That does not look like a Meta access token")
            updates["wa.token_enc"] = vault.encrypt(token)
            updates["wa.token_hint"] = token[-4:]
        with db.tx() as c:
            for key, value in updates.items():
                put_setting(c, key, value)
            if body.clear_token:
                c.execute("DELETE FROM settings WHERE key IN ('wa.token_enc','wa.token_hint')")
            event(c, None, None, None, "settings_changed", ",".join(sorted(k[3:] for k in updates)) or None)
        return await admin_status()

    @app.post("/admin/whatsapp/test", dependencies=[Depends(admin)])
    async def admin_test_whatsapp() -> dict:
        p = wa_parts()
        if not (p["phone_number_id"] and p["access_token"]):
            return {"success": False, "message": "Save the Phone Number ID and the access token first"}
        cfg = WhatsAppConfig(p["phone_number_id"], p["access_token"], p["template_name"], p["template_language"],
                             p["include_button"])
        try:
            info = await sender.check(cfg)
        except DeliveryError as exc:
            return {"success": False, "message": f"Meta refused the call — {exc}"}
        return {"success": True, "message": "Connected to Meta",
                "display_phone_number": info.get("display_phone_number"),
                "verified_name": info.get("verified_name"), "quality_rating": info.get("quality_rating"),
                "template_saved": bool(p["template_name"])}

    def client_view(row) -> dict:
        return {
            "id": row["id"], "name": row["name"], "key_prefix": f"wak_{row['key_id']}", "active": bool(row["active"]),
            "rate_per_minute": row["rate_per_minute"],
            "allowed_country_codes": [x for x in row["allowed_country_codes"].split(",") if x],
            "allowed_ips": [x for x in row["allowed_ips"].split(",") if x],
            "created_at": _iso(row["created_at"]), "revoked_at": _iso(row["revoked_at"]),
            "last_used_at": _iso(row["last_used_at"]),
        }

    @app.post("/admin/clients", dependencies=[Depends(admin)], status_code=201)
    async def admin_create_client(body: ClientBody) -> dict:
        codes = [c.strip() for c in body.allowed_country_codes if c.strip()]
        if any(not re.fullmatch(r"[1-9]\d{0,3}", c) for c in codes):
            raise ApiError(400, "invalid_country_code", "Country codes are calling codes without + such as 1 or 92")
        ips = []
        for raw in body.allowed_ips:
            try:
                ips.append(str(ipaddress.ip_address(raw.strip())))
            except ValueError as exc:
                raise ApiError(400, "invalid_ip", f"{raw!r} is not an IP address") from exc
        key_id, secret, full_key = new_client_key()
        with db.tx() as c:
            cur = c.execute(
                "INSERT INTO clients(key_id, key_hash, name, rate_per_minute, allowed_country_codes, allowed_ips, created_at) "
                "VALUES (?,?,?,?,?,?,?)",
                (key_id, hash_secret(secret), body.name.strip(), body.rate_per_minute or settings.default_rate_per_minute,
                 ",".join(codes), ",".join(ips), clock()))
            row = c.execute("SELECT * FROM clients WHERE id=?", (cur.lastrowid,)).fetchone()
            event(c, row["id"], None, None, "client_created", row["name"])
        return {**client_view(row), "api_key": full_key}

    @app.get("/admin/clients", dependencies=[Depends(admin)])
    async def admin_clients() -> list[dict]:
        with db.tx() as c:
            return [client_view(r) for r in c.execute("SELECT * FROM clients ORDER BY id DESC")]

    @app.delete("/admin/clients/{client_id}", dependencies=[Depends(admin)])
    async def admin_revoke_client(client_id: int) -> dict:
        with db.tx() as c:
            row = c.execute("SELECT * FROM clients WHERE id=?", (client_id,)).fetchone()
            if row is None:
                raise ApiError(404, "not_found", "No such client")
            c.execute("UPDATE clients SET active=0, revoked_at=COALESCE(revoked_at, ?) WHERE id=?", (clock(), client_id))
            event(c, client_id, None, None, "client_revoked", row["name"])
            return client_view(c.execute("SELECT * FROM clients WHERE id=?", (client_id,)).fetchone())

    @app.get("/admin/events", dependencies=[Depends(admin)])
    async def admin_events(limit: int = 50, client_id: int | None = None) -> list[dict]:
        limit = max(1, min(limit, 500))
        with db.tx() as c:
            sql = ("SELECT e.*, c.name AS client_name FROM events e LEFT JOIN clients c ON c.id=e.client_id "
                   + ("WHERE e.client_id=? " if client_id is not None else "") + "ORDER BY e.id DESC LIMIT ?")
            rows = c.execute(sql, ((client_id, limit) if client_id is not None else (limit,))).fetchall()
        return [{"at": _iso(r["ts"]), "client": r["client_name"], "request_id": r["request_id"],
                 "phone": r["phone"], "event": r["event"], "detail": r["detail"]} for r in rows]

    return app
