from fastapi import FastAPI, APIRouter, HTTPException, Header, Depends, Response, Request, Cookie
from dotenv import load_dotenv
from starlette.middleware.cors import CORSMiddleware
from motor.motor_asyncio import AsyncIOMotorClient
import os
import logging
import math
import json
import bcrypt
import secrets as py_secrets
from pathlib import Path
from pydantic import BaseModel, Field, EmailStr
from typing import List, Optional
import uuid
from datetime import datetime, timezone, timedelta
import httpx

ROOT_DIR = Path(__file__).parent
load_dotenv(ROOT_DIR / '.env')

# MongoDB
mongo_url = os.environ['MONGO_URL']
client = AsyncIOMotorClient(mongo_url)
db = client[os.environ['DB_NAME']]

GOOGLE_MAPS_API_KEY = os.environ.get('GOOGLE_MAPS_API_KEY', '')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin123')
PLACES_API_BASE = 'https://places.googleapis.com/v1'

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

app = FastAPI(title="NearMe Admin API")
api_router = APIRouter(prefix="/api")


# ---------- Rate-limit (in-memory sliding window) ----------
# Simple per-IP/per-key limiter. Sufficient for a single-instance deployment.
# For horizontal scale, swap the dict for Redis. Kept dependency-free.
_RATE_BUCKETS: dict[str, list[float]] = {}


def _client_ip(request: Request) -> str:
    fwd = request.headers.get("x-forwarded-for") or ""
    if fwd:
        return fwd.split(",")[0].strip()
    if request.client:
        return request.client.host
    return "unknown"


def rate_limit(scope: str, max_hits: int, window_seconds: int):
    """Dependency: raises 429 when the caller exceeds `max_hits` in the last
    `window_seconds`. Bucket key = scope + client-ip."""
    async def dep(request: Request):
        ip = _client_ip(request)
        key = f"{scope}:{ip}"
        now = datetime.now(timezone.utc).timestamp()
        cutoff = now - window_seconds
        bucket = [t for t in _RATE_BUCKETS.get(key, []) if t > cutoff]
        if len(bucket) >= max_hits:
            retry_after = int(bucket[0] + window_seconds - now) + 1
            raise HTTPException(
                status_code=429,
                detail=f"Too many attempts. Try again in {retry_after}s.",
                headers={"Retry-After": str(retry_after)},
            )
        bucket.append(now)
        _RATE_BUCKETS[key] = bucket
    return dep


# ---------- DB-backed secrets & password helpers ----------
async def get_secret(key: str) -> str:
    doc = await db.app_config.find_one({"_id": "secrets"}, {"_id": 0})
    if doc and doc.get(key):
        return doc[key]
    # Fallback to env
    return os.environ.get(key.upper(), "")


async def current_admin_password() -> str:
    doc = await db.app_config.find_one({"_id": "settings"}, {"_id": 0})
    if doc and doc.get("admin_password"):
        return doc["admin_password"]
    return ADMIN_PASSWORD


# ---------- Auth ----------
async def require_admin(
    request: Request,
    x_admin_token: Optional[str] = Header(default=None),
    authorization: Optional[str] = Header(default=None),
):
    """Admin gate. Accepts EITHER:
      - legacy X-Admin-Token matching ADMIN_PASSWORD (or DB override), OR
      - a JWT session for a user with role 'owner' or 'editor'.
    """
    pw = await current_admin_password()
    if x_admin_token and x_admin_token == pw:
        return True
    try:
        user = await current_user(request, authorization)
    except Exception:
        user = None
    if user and user.get("role") in ("owner", "editor"):
        return True
    raise HTTPException(status_code=401, detail="Unauthorized")


class LoginRequest(BaseModel):
    password: str


@api_router.post("/auth/login")
async def login(req: LoginRequest):
    pw = await current_admin_password()
    if req.password != pw:
        raise HTTPException(status_code=401, detail="Invalid password")
    return {"token": pw, "status": "ok"}


@api_router.get("/auth/verify")
async def verify(_: bool = Depends(require_admin)):
    return {"status": "ok"}


# =============================================================================
# ============ USER AUTH (JWT-like sessions + Emergent Google Auth) ===========
# =============================================================================
SESSION_DAYS = 7
COOKIE_NAME = "session_token"
EMERGENT_SESSION_ENDPOINT = "https://demobackend.emergentagent.com/auth/v1/env/oauth/session-data"


class RegisterRequest(BaseModel):
    email: str
    password: str
    name: str
    phone: Optional[str] = ""
    city: Optional[str] = ""
    referral_code: Optional[str] = ""


class EmailLoginRequest(BaseModel):
    email: str
    password: str


class UserOut(BaseModel):
    user_id: str
    email: str
    name: str
    phone: Optional[str] = ""
    city: Optional[str] = ""
    role: str = "user"
    picture: Optional[str] = None
    google_linked: bool = False
    created_at: str


def _hash_password(pw: str) -> str:
    return bcrypt.hashpw(pw.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")


def _verify_password(pw: str, hashed: str) -> bool:
    try:
        return bcrypt.checkpw(pw.encode("utf-8"), hashed.encode("utf-8"))
    except Exception:
        return False


async def _create_session(user_id: str, method: str) -> str:
    token = py_secrets.token_urlsafe(32)
    await db.user_sessions.insert_one({
        "session_token": token,
        "user_id": user_id,
        "method": method,
        "expires_at": (datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)).isoformat(),
        "created_at": datetime.now(timezone.utc).isoformat(),
    })
    return token


def _set_session_cookie(resp: Response, token: str) -> None:
    resp.set_cookie(
        key=COOKIE_NAME,
        value=token,
        max_age=SESSION_DAYS * 24 * 3600,
        httponly=True,
        secure=True,
        samesite="none",
        path="/",
    )


def _clear_session_cookie(resp: Response) -> None:
    resp.delete_cookie(COOKIE_NAME, path="/")


async def _resolve_session(token: str) -> Optional[dict]:
    if not token:
        return None
    sess = await db.user_sessions.find_one({"session_token": token}, {"_id": 0})
    if not sess:
        return None
    exp = sess.get("expires_at")
    if isinstance(exp, str):
        try:
            exp_dt = datetime.fromisoformat(exp)
        except Exception:
            return None
    else:
        exp_dt = exp
    if exp_dt.tzinfo is None:
        exp_dt = exp_dt.replace(tzinfo=timezone.utc)
    if exp_dt < datetime.now(timezone.utc):
        return None
    user = await db.users.find_one({"user_id": sess["user_id"]}, {"_id": 0, "password_hash": 0})
    return user


async def current_user(
    request: Request,
    authorization: Optional[str] = Header(default=None),
) -> Optional[dict]:
    # 1. Bearer header
    token = None
    if authorization and authorization.lower().startswith("bearer "):
        token = authorization.split(" ", 1)[1].strip()
    # 2. Cookie
    if not token:
        token = request.cookies.get(COOKIE_NAME)
    if not token:
        return None
    return await _resolve_session(token)


async def require_user(user: Optional[dict] = Depends(current_user)) -> dict:
    if not user:
        raise HTTPException(status_code=401, detail="Not authenticated")
    return user


def require_role(*allowed: str):
    async def dep(user: dict = Depends(require_user)) -> dict:
        if user.get("role") not in allowed:
            raise HTTPException(status_code=403, detail=f"Requires one of roles: {list(allowed)}")
        return user
    return dep


async def require_admin_or_user(
    request: Request,
    x_admin_token: Optional[str] = Header(default=None),
    authorization: Optional[str] = Header(default=None),
) -> dict:
    """Backwards-compat: accepts either legacy X-Admin-Token OR a JWT session
    with owner/editor role. Returns a synthetic legacy user for the admin token."""
    pw = await current_admin_password()
    if x_admin_token and x_admin_token == pw:
        return {"user_id": "legacy_admin", "email": "admin@local", "name": "Admin", "role": "owner", "legacy": True}
    user = await current_user(request, authorization)
    if user and user.get("role") in ("owner", "editor"):
        return user
    raise HTTPException(status_code=401, detail="Admin authentication required")


@api_router.post("/auth/register")
async def register(
    req: RegisterRequest,
    response: Response,
    _rl: None = Depends(rate_limit("auth-register", max_hits=5, window_seconds=60)),
):
    email = (req.email or "").strip().lower()
    if not email or "@" not in email:
        raise HTTPException(400, "Valid email is required")
    if len(req.password) < 6:
        raise HTTPException(400, "Password must be at least 6 characters")
    if not req.name.strip():
        raise HTTPException(400, "Name is required")
    existing = await db.users.find_one({"email": email})
    if existing:
        raise HTTPException(409, "Email is already registered")
    # First user becomes owner, everyone else is 'user'
    total = await db.users.count_documents({})
    role = "owner" if total == 0 else "user"
    user_id = f"user_{uuid.uuid4().hex[:12]}"
    referral_code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
    while await db.users.find_one({"referral_code": referral_code}):
        referral_code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
    now = datetime.now(timezone.utc).isoformat()
    referred_by = None
    incoming_code = (req.referral_code or "").strip().upper()
    if incoming_code:
        referrer = await db.users.find_one({"referral_code": incoming_code})
        if referrer:
            referred_by = referrer["user_id"]
    doc = {
        "user_id": user_id,
        "email": email,
        "name": req.name.strip(),
        "phone": (req.phone or "").strip(),
        "city": (req.city or "").strip(),
        "role": role,
        "password_hash": _hash_password(req.password),
        "google_linked": False,
        "picture": None,
        "referral_code": referral_code,
        "referred_by": referred_by,
        "points": 0,
        "created_at": now,
    }
    await db.users.insert_one(doc)
    if referred_by:
        await db.users.update_one({"user_id": user_id}, {"$inc": {"points": 50}})
        await db.users.update_one({"user_id": referred_by}, {"$inc": {"points": 50}})
        await db.point_events.insert_one({"user_id": user_id, "kind": "signup_bonus", "points": 50, "meta": {"referrer": referred_by}, "at": now})
        await db.point_events.insert_one({"user_id": referred_by, "kind": "referral_signup", "points": 50, "meta": {"new_user": user_id, "email": email}, "at": now})
        doc["points"] = 50
    token = await _create_session(user_id, method="email")
    _set_session_cookie(response, token)
    doc.pop("password_hash", None)
    doc.pop("_id", None)
    return {"user": doc, "session_token": token}


@api_router.post("/auth/login-email")
async def login_email(
    req: EmailLoginRequest,
    response: Response,
    _rl: None = Depends(rate_limit("auth-login", max_hits=10, window_seconds=60)),
):
    email = (req.email or "").strip().lower()
    user = await db.users.find_one({"email": email})
    if not user or not user.get("password_hash"):
        raise HTTPException(401, "Invalid email or password")
    if not _verify_password(req.password, user["password_hash"]):
        raise HTTPException(401, "Invalid email or password")
    token = await _create_session(user["user_id"], method="email")
    _set_session_cookie(response, token)
    user.pop("_id", None)
    user.pop("password_hash", None)
    return {"user": user, "session_token": token}


class GoogleSessionRequest(BaseModel):
    session_id: Optional[str] = None


@api_router.post("/auth/session")
async def google_session(
    response: Response,
    body: Optional[GoogleSessionRequest] = None,
    x_session_id: Optional[str] = Header(default=None),
):
    """Exchange a Google `session_id` (from Emergent Auth redirect) for a
    local session. Accepts session_id from header OR JSON body."""
    session_id = x_session_id or (body.session_id if body else None)
    if not session_id:
        raise HTTPException(400, "session_id is required")
    async with httpx.AsyncClient(timeout=15.0) as cli:
        r = await cli.get(EMERGENT_SESSION_ENDPOINT, headers={"X-Session-ID": session_id})
    if r.status_code != 200:
        raise HTTPException(401, "Invalid or expired Google session")
    data = r.json()
    email = (data.get("email") or "").strip().lower()
    if not email:
        raise HTTPException(400, "Email not returned by provider")
    name = data.get("name") or email.split("@")[0]
    picture = data.get("picture")
    session_token = data.get("session_token") or py_secrets.token_urlsafe(32)

    user = await db.users.find_one({"email": email}, {"_id": 0})
    now = datetime.now(timezone.utc).isoformat()
    if user:
        await db.users.update_one(
            {"user_id": user["user_id"]},
            {"$set": {"google_linked": True, "picture": picture, "name": name}},
        )
        user_id = user["user_id"]
        user["google_linked"] = True
        user["picture"] = picture
        user["name"] = name
    else:
        total = await db.users.count_documents({})
        role = "owner" if total == 0 else "user"
        user_id = f"user_{uuid.uuid4().hex[:12]}"
        user = {
            "user_id": user_id,
            "email": email,
            "name": name,
            "phone": "",
            "city": "",
            "role": role,
            "password_hash": None,
            "google_linked": True,
            "picture": picture,
            "created_at": now,
        }
        await db.users.insert_one(user)

    # Use the emergent-provided session_token so cookie == token in DB
    await db.user_sessions.insert_one({
        "session_token": session_token,
        "user_id": user_id,
        "method": "google",
        "expires_at": (datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)).isoformat(),
        "created_at": now,
    })
    _set_session_cookie(response, session_token)
    user.pop("password_hash", None)
    user.pop("_id", None)
    return {"user": user, "session_token": session_token}


@api_router.get("/auth/me")
async def me(user: dict = Depends(require_user)):
    return user


# ---------- First-party Google OAuth (used when the admin has configured
#           google_oauth_client_id + google_oauth_client_secret in /secrets;
#           otherwise the client can fall back to /auth/session (Emergent). ----------
from fastapi.responses import RedirectResponse

GOOGLE_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"
GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
GOOGLE_USERINFO_ENDPOINT = "https://openidconnect.googleapis.com/v1/userinfo"


async def _google_oauth_creds() -> tuple[str, str, str]:
    cid = await get_secret("google_oauth_client_id")
    csec = await get_secret("google_oauth_client_secret")
    redirect = await get_secret("google_oauth_web_redirect_uri")
    return cid, csec, redirect


@api_router.get("/auth/config")
async def auth_config():
    """Public: tells the web + mobile clients which Google flow to use.
    - google_provider == 'own'      → hit /api/auth/google/start
    - google_provider == 'emergent' → open the Emergent redirect URL (legacy)"""
    cid = await get_secret("google_oauth_client_id")
    csec = await get_secret("google_oauth_client_secret")
    ready = bool(cid and csec)
    return {
        "google_provider": "own" if ready else "emergent",
        "own_google_enabled": ready,
    }


@api_router.get("/auth/google/start")
async def google_oauth_start(request: Request, redirect: Optional[str] = None):
    """Kick off the first-party Google OAuth flow. `redirect` is the URL to
    send the user back to after we've minted a session_token (frontend page)."""
    cid, csec, configured_redirect = await _google_oauth_creds()
    if not cid or not csec:
        raise HTTPException(503, "Google OAuth is not configured. Set client id + secret in /secrets.")
    # Backend callback URL: this must be one of the redirect URIs registered
    # in the Google Cloud OAuth client. We prefer the value the admin saved,
    # falling back to the current request's origin.
    if configured_redirect:
        backend_cb = configured_redirect
    else:
        backend_cb = str(request.url_for("google_oauth_callback"))
    # State carries the frontend redirect target so the callback knows where
    # to bounce the user afterwards.
    frontend_redirect = redirect or "/"
    state = py_secrets.token_urlsafe(24)
    await db.oauth_states.insert_one({
        "state": state,
        "frontend_redirect": frontend_redirect,
        "created_at": datetime.now(timezone.utc).isoformat(),
    })
    params = {
        "client_id": cid,
        "redirect_uri": backend_cb,
        "response_type": "code",
        "scope": "openid email profile",
        "access_type": "online",
        "include_granted_scopes": "true",
        "state": state,
        "prompt": "select_account",
    }
    from urllib.parse import urlencode
    return RedirectResponse(url=f"{GOOGLE_AUTH_ENDPOINT}?{urlencode(params)}", status_code=302)


@api_router.get("/auth/google/callback", name="google_oauth_callback")
async def google_oauth_callback(request: Request, code: Optional[str] = None, state: Optional[str] = None, error: Optional[str] = None):
    if error:
        raise HTTPException(400, f"Google returned error: {error}")
    if not code or not state:
        raise HTTPException(400, "Missing code / state")

    st = await db.oauth_states.find_one({"state": state})
    if not st:
        raise HTTPException(400, "Invalid or expired state")
    await db.oauth_states.delete_one({"state": state})

    cid, csec, configured_redirect = await _google_oauth_creds()
    if not cid or not csec:
        raise HTTPException(503, "Google OAuth is not configured")
    backend_cb = configured_redirect or str(request.url_for("google_oauth_callback"))

    # 1. Exchange code for tokens
    async with httpx.AsyncClient(timeout=15.0) as cli:
        tr = await cli.post(GOOGLE_TOKEN_ENDPOINT, data={
            "code": code,
            "client_id": cid,
            "client_secret": csec,
            "redirect_uri": backend_cb,
            "grant_type": "authorization_code",
        })
        if tr.status_code != 200:
            raise HTTPException(401, f"Token exchange failed: {tr.text[:200]}")
        tokens = tr.json()
        access_token = tokens.get("access_token")

        # 2. Fetch user profile
        ur = await cli.get(GOOGLE_USERINFO_ENDPOINT, headers={"Authorization": f"Bearer {access_token}"})
        if ur.status_code != 200:
            raise HTTPException(401, f"UserInfo failed: {ur.text[:200]}")
        profile = ur.json()

    email = (profile.get("email") or "").strip().lower()
    if not email:
        raise HTTPException(400, "Google did not return an email")
    name = profile.get("name") or email.split("@")[0]
    picture = profile.get("picture")

    # 3. Upsert user + create session
    user = await db.users.find_one({"email": email}, {"_id": 0})
    now = datetime.now(timezone.utc).isoformat()
    if user:
        await db.users.update_one(
            {"user_id": user["user_id"]},
            {"$set": {"google_linked": True, "picture": picture, "name": name}},
        )
        user_id = user["user_id"]
    else:
        total = await db.users.count_documents({})
        role = "owner" if total == 0 else "user"
        user_id = f"user_{uuid.uuid4().hex[:12]}"
        referral_code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
        while await db.users.find_one({"referral_code": referral_code}):
            referral_code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
        await db.users.insert_one({
            "user_id": user_id,
            "email": email,
            "name": name,
            "phone": "",
            "city": "",
            "role": role,
            "password_hash": None,
            "google_linked": True,
            "picture": picture,
            "referral_code": referral_code,
            "referred_by": None,
            "points": 0,
            "created_at": now,
        })

    token = await _create_session(user_id, method="google")

    # 4. Bounce user back to the frontend page they originally requested,
    # embedding the session_token in the URL fragment (never sent to server).
    from urllib.parse import urlparse, urlencode
    frontend_redirect = st.get("frontend_redirect") or "/"
    parsed = urlparse(frontend_redirect)
    join_char = "&" if parsed.fragment else ""
    final_url = f"{frontend_redirect}#{parsed.fragment}{join_char}session_token={token}"
    resp = RedirectResponse(url=final_url, status_code=302)
    _set_session_cookie(resp, token)
    return resp


@api_router.post("/auth/logout")
async def logout(request: Request, response: Response, authorization: Optional[str] = Header(default=None)):
    token = None
    if authorization and authorization.lower().startswith("bearer "):
        token = authorization.split(" ", 1)[1].strip()
    if not token:
        token = request.cookies.get(COOKIE_NAME)
    if token:
        await db.user_sessions.delete_one({"session_token": token})
    _clear_session_cookie(response)
    return {"status": "ok"}


# ---------- User management (admin) ----------
@api_router.get("/users")
async def list_users(_: dict = Depends(require_role("owner", "editor"))):
    docs = await db.users.find({}, {"_id": 0, "password_hash": 0}).sort("created_at", -1).to_list(500)
    return docs


class RoleChange(BaseModel):
    role: str


@api_router.put("/users/{user_id}/role")
async def change_role(user_id: str, req: RoleChange, admin: dict = Depends(require_role("owner"))):
    if req.role not in ("owner", "editor", "viewer", "user"):
        raise HTTPException(400, "Invalid role")
    target = await db.users.find_one({"user_id": user_id}, {"_id": 0})
    if not target:
        raise HTTPException(404, "User not found")
    # Protect owner accounts: an owner's role can NEVER be changed via the API.
    # This prevents accidental demotion (which locked the user out last time).
    if target.get("role") == "owner":
        raise HTTPException(403, "Owner role is protected and cannot be changed. Demote the account manually in the database if truly required.")
    r = await db.users.update_one({"user_id": user_id}, {"$set": {"role": req.role}})
    if r.matched_count == 0:
        raise HTTPException(404, "User not found")
    return {"status": "ok"}


@api_router.delete("/users/{user_id}")
async def delete_user(user_id: str, admin: dict = Depends(require_role("owner"))):
    if admin.get("user_id") == user_id:
        raise HTTPException(400, "You cannot delete your own account")
    target = await db.users.find_one({"user_id": user_id}, {"_id": 0})
    if not target:
        raise HTTPException(404, "User not found")
    if target.get("role") == "owner":
        raise HTTPException(403, "Owner accounts are protected and cannot be deleted.")
    r = await db.users.delete_one({"user_id": user_id})
    await db.user_sessions.delete_many({"user_id": user_id})
    if r.deleted_count == 0:
        raise HTTPException(404, "User not found")
    return {"status": "ok"}


# ---------- Referrals & Points ----------
async def _ensure_referral_fields(user_id: str) -> dict:
    """Backfill referral_code / points on any pre-existing user."""
    u = await db.users.find_one({"user_id": user_id}, {"_id": 0})
    if not u:
        return {}
    updates = {}
    if not u.get("referral_code"):
        code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
        while await db.users.find_one({"referral_code": code}):
            code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
        updates["referral_code"] = code
    if "points" not in u:
        updates["points"] = 0
    if updates:
        await db.users.update_one({"user_id": user_id}, {"$set": updates})
        u.update(updates)
    return u


@api_router.get("/referrals/me")
async def my_referrals(user: dict = Depends(require_user)):
    u = await _ensure_referral_fields(user["user_id"])
    referred = await db.users.find(
        {"referred_by": user["user_id"]},
        {"_id": 0, "user_id": 1, "name": 1, "email": 1, "created_at": 1},
    ).sort("created_at", -1).to_list(200)
    events = await db.point_events.find(
        {"user_id": user["user_id"]}, {"_id": 0},
    ).sort("at", -1).to_list(50)
    return {
        "code": u.get("referral_code"),
        "points": u.get("points", 0),
        "referred_users": referred,
        "recent_events": events,
    }


class ApplyCodeRequest(BaseModel):
    code: str


@api_router.post("/referrals/apply-code")
async def apply_code(req: ApplyCodeRequest, user: dict = Depends(require_user)):
    """Apply a referral code AFTER signup (one-shot). Used when the user forgot
    to enter the code during registration."""
    if user.get("referred_by"):
        raise HTTPException(400, "You have already been referred")
    code = (req.code or "").strip().upper()
    referrer = await db.users.find_one({"referral_code": code})
    if not referrer:
        raise HTTPException(404, "Invalid referral code")
    if referrer["user_id"] == user["user_id"]:
        raise HTTPException(400, "You cannot refer yourself")
    now = datetime.now(timezone.utc).isoformat()
    await db.users.update_one(
        {"user_id": user["user_id"]},
        {"$set": {"referred_by": referrer["user_id"]}, "$inc": {"points": 50}},
    )
    await db.users.update_one({"user_id": referrer["user_id"]}, {"$inc": {"points": 50}})
    await db.point_events.insert_one({"user_id": user["user_id"], "kind": "signup_bonus", "points": 50, "meta": {"referrer": referrer["user_id"]}, "at": now})
    await db.point_events.insert_one({"user_id": referrer["user_id"], "kind": "referral_signup", "points": 50, "meta": {"new_user": user["user_id"]}, "at": now})
    return {"status": "ok", "points_awarded": 50}


@api_router.get("/referrals/summary")
async def referral_summary(_: bool = Depends(require_admin)):
    """Admin view: top referrers + total points issued."""
    top = await db.users.aggregate([
        {"$match": {"points": {"$gt": 0}}},
        {"$project": {"_id": 0, "user_id": 1, "name": 1, "email": 1, "points": 1, "referral_code": 1}},
        {"$sort": {"points": -1}},
        {"$limit": 20},
    ]).to_list(20)
    total_points = 0
    async for u in db.users.find({}, {"points": 1, "_id": 0}):
        total_points += u.get("points", 0) or 0
    total_referrals = await db.users.count_documents({"referred_by": {"$ne": None, "$exists": True}})
    return {
        "total_points_issued": total_points,
        "total_referrals": total_referrals,
        "top_referrers": top,
    }


# =============================================================================



class PasswordChange(BaseModel):
    current_password: str
    new_password: str


@api_router.put("/settings/password")
async def change_password(req: PasswordChange, _: bool = Depends(require_admin)):
    cur = await current_admin_password()
    if req.current_password != cur:
        raise HTTPException(status_code=400, detail="Current password is incorrect")
    if len(req.new_password) < 4:
        raise HTTPException(status_code=400, detail="New password must be at least 4 characters")
    await db.app_config.update_one(
        {"_id": "settings"},
        {"$set": {"admin_password": req.new_password, "updated_at": datetime.now(timezone.utc).isoformat()}},
        upsert=True,
    )
    return {"status": "ok", "token": req.new_password}


# ---------- Secrets ----------
SECRET_KEYS = [
    "google_maps_api_key",
    "directions_api_key",
    "weather_api_key",
    "admob_android_app_id",
    "admob_ios_app_id",
    "backend_url",
    "google_oauth_client_id",
    "google_oauth_client_secret",
    "google_oauth_web_redirect_uri",
    "play_store_url",
    "apple_store_url",
]


def _mask(v: str) -> str:
    if not v:
        return ""
    if len(v) <= 8:
        return "•" * len(v)
    return v[:4] + "•" * (len(v) - 8) + v[-4:]


@api_router.get("/secrets/{key}/reveal")
async def reveal_secret(key: str, _: bool = Depends(require_admin)):
    """Owner-only plaintext reveal — used by the Secrets page eye toggle so the
    account holder can copy their own key without me ever printing it in chat
    or logs. Not indexed by any middleware."""
    if key not in SECRET_KEYS:
        raise HTTPException(status_code=404, detail="Unknown secret key")
    doc = await db.app_config.find_one({"_id": "secrets"}, {"_id": 0}) or {}
    val = doc.get(key) or (os.environ.get(key.upper(), "") if key == "google_maps_api_key" else "")
    return {"key": key, "value": val, "set": bool(val)}


@api_router.get("/secrets")
async def get_secrets(_: bool = Depends(require_admin)):
    doc = await db.app_config.find_one({"_id": "secrets"}, {"_id": 0}) or {}
    out = {}
    for k in SECRET_KEYS:
        val = doc.get(k) or (os.environ.get(k.upper(), "") if k == "google_maps_api_key" else "")
        out[k] = {
            "set": bool(val),
            "masked": _mask(val),
            "source": "db" if doc.get(k) else ("env" if val else "none"),
        }
    out["updated_at"] = doc.get("updated_at")
    return out


class SecretsUpdate(BaseModel):
    google_maps_api_key: Optional[str] = None
    directions_api_key: Optional[str] = None
    weather_api_key: Optional[str] = None
    admob_android_app_id: Optional[str] = None
    admob_ios_app_id: Optional[str] = None
    backend_url: Optional[str] = None
    google_oauth_client_id: Optional[str] = None
    google_oauth_client_secret: Optional[str] = None
    google_oauth_web_redirect_uri: Optional[str] = None
    play_store_url: Optional[str] = None
    apple_store_url: Optional[str] = None


@api_router.put("/secrets")
async def update_secrets(req: SecretsUpdate, _: bool = Depends(require_admin)):
    patch = {k: v for k, v in req.dict().items() if v is not None}
    patch["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one({"_id": "secrets"}, {"$set": patch}, upsert=True)
    doc = await db.app_config.find_one({"_id": "secrets"}, {"_id": 0}) or {}
    out = {}
    for k in SECRET_KEYS:
        val = doc.get(k) or (os.environ.get(k.upper(), "") if k == "google_maps_api_key" else "")
        out[k] = {
            "set": bool(val),
            "masked": _mask(val),
            "source": "db" if doc.get(k) else ("env" if val else "none"),
        }
    out["updated_at"] = doc.get("updated_at")
    return out


# ---------- Helpers ----------
def _google_error_detail(text: str):
    try:
        return json.loads(text)
    except Exception:
        return text


def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    R = 6371.0
    p1 = math.radians(lat1)
    p2 = math.radians(lat2)
    dp = math.radians(lat2 - lat1)
    dl = math.radians(lon2 - lon1)
    a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    return R * c


# ---------- Models ----------
class NearbyRequest(BaseModel):
    latitude: float
    longitude: float
    included_types: List[str] = []
    keyword: Optional[str] = None            # if set, uses places:searchText first
    radius: float = 5000.0
    max_results: int = 20


class Place(BaseModel):
    id: str
    name: str
    address: Optional[str] = None
    latitude: float
    longitude: float
    primary_type: Optional[str] = None
    distance_km: Optional[float] = None
    rating: Optional[float] = None
    user_rating_count: Optional[int] = None
    phone: Optional[str] = None
    website: Optional[str] = None
    open_now: Optional[bool] = None


class FavoriteCreate(BaseModel):
    place_id: str
    name: str
    address: Optional[str] = None
    latitude: float
    longitude: float
    category: Optional[str] = None


class Favorite(BaseModel):
    id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    place_id: str
    name: str
    address: Optional[str] = None
    latitude: float
    longitude: float
    category: Optional[str] = None
    created_at: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


# ---------- Public Routes ----------
@api_router.get("/")
async def root():
    return {
        "message": "NearMe Admin API up",
        "has_google_key": bool(GOOGLE_MAPS_API_KEY),
        "version": "1.0.0",
    }


@api_router.get("/status")
async def status():
    """Public health/status endpoint used by the admin dashboard."""
    fav_count = await db.favorites.count_documents({})
    key = await get_secret("google_maps_api_key")
    cats_count = await db.categories.count_documents({})
    if cats_count == 0:
        cats_count = len(DEFAULT_CATEGORIES)
    return {
        "api": "ok",
        "mongo": "ok",
        "google_places_configured": bool(key),
        "favorites_count": fav_count,
        "categories_count": cats_count,
        "timestamp": datetime.now(timezone.utc).isoformat(),
    }


@api_router.get("/categories-legacy-noop")
async def _legacy_noop():
    return {}


@api_router.get("/public/app-store-urls")
async def public_app_store_urls():
    """Public — used by the Landing page to render the App Store / Play Store
    badges. Returns empty strings when not configured (Landing hides them)."""
    return {
        "play_store_url": await get_secret("play_store_url") or "",
        "apple_store_url": await get_secret("apple_store_url") or "",
    }


# ---------- Places (Google Proxy) ----------
def _google_permission_error(status: int, body_txt: str) -> HTTPException:
    detail = _google_error_detail(body_txt)
    if status == 403 and ("API_KEY_SERVICE_BLOCKED" in body_txt or "SERVICE_DISABLED" in body_txt):
        return HTTPException(
            status_code=503,
            detail=(
                "Places API (New) is not enabled on your Google Cloud project. "
                "Open https://console.cloud.google.com/apis/library/places.googleapis.com "
                "and click Enable, then retry."
            ),
        )
    if status == 403 and "API key not valid" in body_txt:
        return HTTPException(status_code=401, detail="Google Maps API key is invalid — update it in /secrets.")
    return HTTPException(status_code=status, detail=detail)


_PLACES_FIELD_MASK = (
    "places.id,places.displayName,places.formattedAddress,"
    "places.location,places.primaryType,places.rating,"
    "places.userRatingCount,places.nationalPhoneNumber,"
    "places.internationalPhoneNumber,places.websiteUri,"
    "places.currentOpeningHours.openNow"
)


def _parse_places_response(data: dict, origin_lat: float, origin_lng: float) -> List[Place]:
    out: List[Place] = []
    for p in data.get("places", []):
        loc = p.get("location") or {}
        lat, lng = loc.get("latitude"), loc.get("longitude")
        if lat is None or lng is None:
            continue
        out.append(Place(
            id=p.get("id", ""),
            name=(p.get("displayName") or {}).get("text", "Unknown"),
            address=p.get("formattedAddress"),
            latitude=lat,
            longitude=lng,
            primary_type=p.get("primaryType"),
            distance_km=round(haversine_km(origin_lat, origin_lng, lat, lng), 2),
            rating=p.get("rating"),
            user_rating_count=p.get("userRatingCount"),
            phone=p.get("nationalPhoneNumber") or p.get("internationalPhoneNumber"),
            website=p.get("websiteUri"),
            open_now=(p.get("currentOpeningHours") or {}).get("openNow"),
        ))
    return out


async def _places_search_nearby(key: str, req: NearbyRequest) -> List[Place]:
    if not req.included_types:
        return []
    body = {
        "includedTypes": req.included_types,
        "maxResultCount": min(max(req.max_results, 1), 20),
        "rankPreference": "DISTANCE",
        "locationRestriction": {
            "circle": {
                "center": {"latitude": req.latitude, "longitude": req.longitude},
                "radius": req.radius,
            }
        },
    }
    headers = {"Content-Type": "application/json", "X-Goog-Api-Key": key, "X-Goog-FieldMask": _PLACES_FIELD_MASK}
    async with httpx.AsyncClient(timeout=15.0) as cli:
        r = await cli.post(f"{PLACES_API_BASE}/places:searchNearby", json=body, headers=headers)
    if r.status_code == 200:
        return _parse_places_response(r.json(), req.latitude, req.longitude)
    raise _google_permission_error(r.status_code, r.text or "")


async def _places_search_text(key: str, req: NearbyRequest) -> List[Place]:
    """Free-form text (keyword) search — matches place names/tags, not just types.
    Used for keyword categories like 'Aadhaar Seva Kendra' or free-text queries."""
    if not (req.keyword or "").strip():
        return []
    body = {
        "textQuery": req.keyword,
        "maxResultCount": min(max(req.max_results, 1), 20),
        "locationBias": {
            "circle": {
                "center": {"latitude": req.latitude, "longitude": req.longitude},
                "radius": req.radius,
            }
        },
    }
    headers = {"Content-Type": "application/json", "X-Goog-Api-Key": key, "X-Goog-FieldMask": _PLACES_FIELD_MASK}
    async with httpx.AsyncClient(timeout=15.0) as cli:
        r = await cli.post(f"{PLACES_API_BASE}/places:searchText", json=body, headers=headers)
    if r.status_code == 200:
        return _parse_places_response(r.json(), req.latitude, req.longitude)
    raise _google_permission_error(r.status_code, r.text or "")


@api_router.post("/places/nearby", response_model=List[Place])
async def nearby_places(req: NearbyRequest):
    """Unified places search.

    Behaviour:
      1. If `keyword` is set     → try `places:searchText` first.
      2. If keyword yields 0     → fall back to `places:searchNearby` with types.
      3. If only `included_types` given → nearby-by-type only.

    This supports the Aadhaar-Seva-Kendra pattern: keyword='Aadhaar Seva Kendra',
    included_types=['government_office']. Google's text-search returns AADHAAR
    centers by name; if a region has none we fall back to nearby government
    offices instead of returning empty."""
    key = await get_secret("google_maps_api_key")
    if not key:
        raise HTTPException(status_code=500, detail="Google API key not configured. Set it in Secrets or backend/.env")

    if not req.included_types and not (req.keyword or "").strip():
        raise HTTPException(status_code=400, detail="Provide `included_types` or `keyword` (or both).")

    if (req.keyword or "").strip():
        try:
            results = await _places_search_text(key, req)
            if results:
                return results
        except HTTPException:
            raise
        # keyword returned 0 → fall through to type-based fallback

    if req.included_types:
        return await _places_search_nearby(key, req)
    return []


# ---------- AI Local Concierge ----------
class AiSearchRequest(BaseModel):
    query: str
    latitude: float
    longitude: float
    radius: float = 5000.0
    max_results: int = 20


class AiSearchResponse(BaseModel):
    keyword: Optional[str] = None
    included_types: List[str] = []
    intent_summary: Optional[str] = None
    places: List[Place] = []


# Google's supported place types (a curated subset that covers ~99% of use cases).
# We whitelist so the LLM can't invent tokens Google rejects.
_KNOWN_GOOGLE_TYPES = {
    "restaurant", "cafe", "bakery", "bar", "meal_takeaway", "meal_delivery",
    "food", "grocery_or_supermarket", "supermarket", "convenience_store",
    "shopping_mall", "clothing_store", "electronics_store", "book_store",
    "hospital", "pharmacy", "dentist", "doctor", "veterinary_care",
    "gym", "spa", "beauty_salon", "hair_care",
    "bank", "atm", "post_office", "gas_station", "car_repair",
    "airport", "bus_station", "train_station", "subway_station", "taxi_stand",
    "lodging", "hotel", "campground", "rv_park",
    "park", "tourist_attraction", "museum", "zoo", "amusement_park",
    "movie_theater", "night_club", "casino", "stadium",
    "police", "fire_station", "school", "primary_school", "secondary_school",
    "university", "library", "church", "hindu_temple", "mosque", "synagogue",
    "government_office", "city_hall", "courthouse", "embassy",
    "plumber", "electrician", "locksmith", "roofing_contractor", "painter",
    "moving_company", "storage", "laundry",
    "florist", "pet_store", "hardware_store", "furniture_store",
    "real_estate_agency", "insurance_agency", "lawyer", "accounting",
    "car_dealer", "car_rental", "car_wash", "parking",
    "physiotherapist", "dental_clinic", "optometrist",
}


@api_router.post("/places/ai-search", response_model=AiSearchResponse)
async def ai_local_concierge(req: AiSearchRequest):
    """Parse free-form natural language ("Find me a plumber that fixes leaky
    sinks", "Quiet café with wifi for a 2-hour meeting", or a plain keyword
    like "cafe") into a Places API query, then run the same keyword→type
    fallback used by /places/nearby.

    Uses Emergent's Claude Sonnet 4.5 (Anthropic) via the emergentintegrations
    library."""
    query = (req.query or "").strip()
    if not query:
        raise HTTPException(400, "Query is required")

    llm_key = os.environ.get("EMERGENT_LLM_KEY")
    if not llm_key:
        raise HTTPException(503, "AI concierge is not configured (missing EMERGENT_LLM_KEY).")

    system_prompt = (
        "You are a local-search intent parser for a maps app. Given a user's "
        "free-form query, return STRICT JSON with three fields and nothing else:\n"
        '  {"keyword": string|null, "included_types": string[], "intent_summary": string}\n\n'
        "Rules:\n"
        "- 'keyword' is the best short search phrase for Google Places text-search. "
        "  For proper nouns / brand names use them verbatim (e.g. 'Aadhaar Seva Kendra').\n"
        "- 'included_types' contains 0-3 Google Places (New) type tokens that best "
        "  match the intent, drawn ONLY from this whitelist:\n"
        f"  {sorted(_KNOWN_GOOGLE_TYPES)}\n"
        "- 'intent_summary' is one short human sentence that describes what the "
        "  user wants, in third person (e.g. 'Nearby plumbers who fix sinks').\n"
        "- If the query is a single word (e.g. 'cafe'), set keyword=that word "
        "  AND choose one matching type.\n"
        "- Never output markdown, comments, code fences or extra fields.\n"
        "- Never output null for included_types — use [] instead.\n"
    )

    from emergentintegrations.llm.chat import LlmChat, UserMessage
    chat = (
        LlmChat(
            api_key=llm_key,
            session_id=f"ai-search-{uuid.uuid4().hex[:8]}",
            system_message=system_prompt,
        )
        .with_model("anthropic", "claude-sonnet-4-5-20250929")
    )

    try:
        raw = await chat.send_message(UserMessage(text=query))
    except Exception as e:
        logger.warning(f"AI concierge LLM call failed: {e}")
        raise HTTPException(502, f"AI parse failed: {e}")

    text = raw if isinstance(raw, str) else str(raw)
    # Trim any accidental prose around the JSON.
    lo, hi = text.find("{"), text.rfind("}")
    if lo == -1 or hi == -1:
        raise HTTPException(502, f"AI did not return JSON: {text[:200]}")
    try:
        parsed = json.loads(text[lo:hi + 1])
    except Exception:
        raise HTTPException(502, f"AI returned invalid JSON: {text[:200]}")

    keyword = (parsed.get("keyword") or "").strip() or None
    types = [t for t in (parsed.get("included_types") or []) if t in _KNOWN_GOOGLE_TYPES]
    intent = parsed.get("intent_summary")

    key = await get_secret("google_maps_api_key")
    if not key:
        raise HTTPException(500, "Google API key not configured. Set it in /secrets.")

    search_req = NearbyRequest(
        latitude=req.latitude,
        longitude=req.longitude,
        included_types=types,
        keyword=keyword,
        radius=req.radius,
        max_results=req.max_results,
    )
    places: List[Place] = []
    if keyword:
        try:
            places = await _places_search_text(key, search_req)
        except HTTPException:
            raise
    if not places and types:
        places = await _places_search_nearby(key, search_req)

    return AiSearchResponse(keyword=keyword, included_types=types, intent_summary=intent, places=places)


@api_router.get("/places/{place_id}", response_model=Place)
async def place_details(place_id: str, lat: float = 0.0, lng: float = 0.0):
    """PUBLIC — mobile app fetches full details for a place tapped from the list."""
    key = await get_secret("google_maps_api_key")
    if not key:
        raise HTTPException(status_code=500, detail="Google API key not configured")
    url = f"{PLACES_API_BASE}/places/{place_id}"
    headers = {
        "X-Goog-Api-Key": key,
        "X-Goog-FieldMask": (
            "id,displayName,formattedAddress,location,primaryType,rating,"
            "userRatingCount,nationalPhoneNumber,internationalPhoneNumber,"
            "websiteUri,currentOpeningHours.openNow"
        ),
    }
    async with httpx.AsyncClient(timeout=15.0) as cli:
        r = await cli.get(url, headers=headers)
    if r.status_code != 200:
        raise HTTPException(status_code=r.status_code, detail=_google_error_detail(r.text))
    p = r.json()
    loc = p.get("location") or {}
    plat = loc.get("latitude") or 0.0
    plng = loc.get("longitude") or 0.0
    dist = haversine_km(lat, lng, plat, plng) if (lat or lng) else None
    return Place(
        id=p.get("id", place_id),
        name=(p.get("displayName") or {}).get("text", "Unknown"),
        address=p.get("formattedAddress"),
        latitude=plat,
        longitude=plng,
        primary_type=p.get("primaryType"),
        distance_km=(round(dist, 2) if dist is not None else None),
        rating=p.get("rating"),
        user_rating_count=p.get("userRatingCount"),
        phone=p.get("nationalPhoneNumber") or p.get("internationalPhoneNumber"),
        website=p.get("websiteUri"),
        open_now=(p.get("currentOpeningHours") or {}).get("openNow"),
    )


# ---------- Favorites ----------
@api_router.post("/favorites", response_model=Favorite)
async def add_favorite(fav: FavoriteCreate, _: bool = Depends(require_admin)):
    obj = Favorite(**fav.dict())
    await db.favorites.insert_one(obj.dict())
    return obj


@api_router.get("/favorites", response_model=List[Favorite])
async def list_favorites(_: bool = Depends(require_admin)):
    docs = await db.favorites.find({}, {"_id": 0}).to_list(500)
    return [Favorite(**d) for d in docs]


@api_router.delete("/favorites/{fav_id}")
async def delete_favorite(fav_id: str, _: bool = Depends(require_admin)):
    result = await db.favorites.delete_one({"id": fav_id})
    return {"status": "ok", "deleted": result.deleted_count}


# ---------- Ad Config ----------
DEFAULT_AD_CONFIG = {
    "enabled": True,
    "frequency_minutes": 5,
    "interstitial_frequency": 3,
    "max_per_session": 5,
    "video_ad": {
        "enabled": True,
        "show_on": "place_details",
        "default_skip_after_seconds": 5,
        "frequency": 2,
        "admob_fallback": {
            "enabled": True,
            "androidUnitId": "",
            "iosUnitId": "",
            "testAndroidUnitId": "ca-app-pub-3940256099942544/5224354917",
            "testIosUnitId": "ca-app-pub-3940256099942544/1712485313",
        },
        "rules": [
            {
                "id": "default_all",
                "name": "Default video (all categories)",
                "category": "all",
                "city": "",
                "video_url": "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
                "click_through_url": "https://nearme.app",
                "advertiser_name": "NearMe",
                "cta_text": "Learn more",
                "skip_after_seconds": 5,
                "priority": 0,
                "enabled": True,
            },
        ],
    },
    "placements": {
        "home_screen": {
            "banner": {
                "enabled": True,
                "position": "bottom",
                "androidUnitId": "",
                "iosUnitId": "",
                "testAndroidUnitId": "ca-app-pub-3940256099942544/6300978111",
                "testIosUnitId": "ca-app-pub-3940256099942544/2934735716",
                "placeholderTitle": "Promote your business on NearMe",
            },
            "interstitial": {
                "enabled": False,
                "androidUnitId": "",
                "iosUnitId": "",
                "testAndroidUnitId": "ca-app-pub-3940256099942544/1033173712",
                "testIosUnitId": "ca-app-pub-3940256099942544/4411468910",
            },
        },
        "place_list": {
            "banner": {
                "enabled": True,
                "position": "top",
                "androidUnitId": "",
                "iosUnitId": "",
                "testAndroidUnitId": "ca-app-pub-3940256099942544/6300978111",
                "testIosUnitId": "ca-app-pub-3940256099942544/2934735716",
                "placeholderTitle": "Reach customers searching nearby",
            },
            "interstitial": {
                "enabled": True,
                "androidUnitId": "",
                "iosUnitId": "",
                "testAndroidUnitId": "ca-app-pub-3940256099942544/1033173712",
                "testIosUnitId": "ca-app-pub-3940256099942544/4411468910",
            },
        },
        "place_details": {
            "banner": {
                "enabled": True,
                "position": "bottom",
                "androidUnitId": "",
                "iosUnitId": "",
                "testAndroidUnitId": "ca-app-pub-3940256099942544/6300978111",
                "testIosUnitId": "ca-app-pub-3940256099942544/2934735716",
                "placeholderTitle": "Sponsored: Local Business",
            },
            "interstitial": {
                "enabled": False,
                "androidUnitId": "",
                "iosUnitId": "",
                "testAndroidUnitId": "ca-app-pub-3940256099942544/1033173712",
                "testIosUnitId": "ca-app-pub-3940256099942544/4411468910",
            },
        },
    },
}


class AdConfigUpdate(BaseModel):
    enabled: Optional[bool] = None
    frequency_minutes: Optional[int] = None
    interstitial_frequency: Optional[int] = None
    max_per_session: Optional[int] = None
    placements: Optional[dict] = None
    video_ad: Optional[dict] = None


@api_router.get("/ad-config")
async def get_ad_config():
    """PUBLIC — mobile app fetches this to render banners/interstitials/video ads."""
    doc = await db.app_config.find_one({"_id": "ad_config"})
    if not doc:
        await db.app_config.insert_one({"_id": "ad_config", **DEFAULT_AD_CONFIG})
        return DEFAULT_AD_CONFIG
    doc.pop("_id", None)
    return doc


@api_router.put("/ad-config")
async def update_ad_config(update: AdConfigUpdate, _: bool = Depends(require_admin)):
    current = await db.app_config.find_one({"_id": "ad_config"})
    if current:
        current.pop("_id", None)
    else:
        current = dict(DEFAULT_AD_CONFIG)
    patch = {k: v for k, v in update.dict().items() if v is not None}
    # Snapshot previous state before applying update
    if current and any(k != "updated_at" for k in current.keys()):
        snap = {
            "kind": "ad_config",
            "snapshot_at": datetime.now(timezone.utc).isoformat(),
            "reason": "pre-update",
            "data": {k: v for k, v in current.items() if k != "updated_at"},
        }
        await db.config_history.insert_one(snap)
    current.update(patch)
    current["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one(
        {"_id": "ad_config"}, {"$set": current}, upsert=True
    )
    return current


@api_router.post("/ad-config/reset")
async def reset_ad_config(_: bool = Depends(require_admin)):
    cur = await db.app_config.find_one({"_id": "ad_config"})
    if cur:
        cur.pop("_id", None)
        await db.config_history.insert_one({
            "kind": "ad_config",
            "snapshot_at": datetime.now(timezone.utc).isoformat(),
            "reason": "pre-reset",
            "data": {k: v for k, v in cur.items() if k != "updated_at"},
        })
    reset = dict(DEFAULT_AD_CONFIG)
    reset["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one(
        {"_id": "ad_config"}, {"$set": reset}, upsert=True
    )
    return reset


@api_router.get("/ad-config/history")
async def ad_config_history(_: bool = Depends(require_admin)):
    docs = await db.config_history.find({"kind": "ad_config"}, {"_id": 0}).sort(
        "snapshot_at", -1
    ).to_list(100)
    # Attach an id (index) for restore lookup by snapshot_at
    return [{"id": d["snapshot_at"], "snapshot_at": d["snapshot_at"], "reason": d.get("reason", ""), "summary": _summarize_ad_config(d.get("data", {}))} for d in docs]


def _summarize_ad_config(data: dict) -> dict:
    v = data.get("video_ad") or {}
    p = data.get("placements") or {}
    return {
        "enabled": data.get("enabled"),
        "video_ads_enabled": v.get("enabled"),
        "video_rules": len(v.get("rules") or []),
        "placements_enabled": sum(1 for pl in p.values() if (pl or {}).get("banner", {}).get("enabled") or (pl or {}).get("interstitial", {}).get("enabled")),
    }


@api_router.post("/ad-config/restore/{snapshot_at}")
async def ad_config_restore(snapshot_at: str, _: bool = Depends(require_admin)):
    snap = await db.config_history.find_one({"kind": "ad_config", "snapshot_at": snapshot_at})
    if not snap:
        raise HTTPException(404, "Snapshot not found")
    # Snapshot current before restoring
    cur = await db.app_config.find_one({"_id": "ad_config"})
    if cur:
        cur.pop("_id", None)
        await db.config_history.insert_one({
            "kind": "ad_config",
            "snapshot_at": datetime.now(timezone.utc).isoformat(),
            "reason": f"pre-restore-of-{snapshot_at}",
            "data": {k: v for k, v in cur.items() if k != "updated_at"},
        })
    data = snap.get("data") or {}
    data["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one({"_id": "ad_config"}, {"$set": data}, upsert=True)
    return data


# ---------- Analytics ----------
class AnalyticsEvent(BaseModel):
    event: str  # "impression" | "click"
    rule_id: Optional[str] = None
    category: Optional[str] = None


@api_router.post("/analytics/track")
async def analytics_track(ev: AnalyticsEvent):
    """PUBLIC — mobile app posts ad impressions & clicks here."""
    if ev.event not in ("impression", "click"):
        raise HTTPException(400, "event must be 'impression' or 'click'")
    doc = {
        "event": ev.event,
        "rule_id": ev.rule_id or "unknown",
        "category": ev.category or "unknown",
        "at": datetime.now(timezone.utc).isoformat(),
    }
    await db.analytics_events.insert_one(doc)
    return {"status": "ok"}


@api_router.get("/analytics/summary")
async def analytics_summary(_: bool = Depends(require_admin)):
    # Ad rule performance
    pipeline_rules = [
        {"$group": {
            "_id": {"rule_id": "$rule_id", "event": "$event"},
            "count": {"$sum": 1},
        }}
    ]
    rows = await db.analytics_events.aggregate(pipeline_rules).to_list(1000)
    rules_map = {}
    for r in rows:
        rid = r["_id"]["rule_id"]
        evt = r["_id"]["event"]
        rules_map.setdefault(rid, {"rule_id": rid, "impressions": 0, "clicks": 0})
        rules_map[rid][evt + "s"] = r["count"]
    rules_perf = list(rules_map.values())
    for r in rules_perf:
        imp = r.get("impressions") or 0
        r["ctr"] = round((r.get("clicks", 0) / imp) * 100, 2) if imp else 0.0

    # Favorites per category
    fav_agg = await db.favorites.aggregate([
        {"$group": {"_id": "$category", "count": {"$sum": 1}}},
        {"$sort": {"count": -1}},
    ]).to_list(200)
    fav_by_cat = [{"category": (r["_id"] or "unknown"), "count": r["count"]} for r in fav_agg]

    totals = {
        "impressions": sum(r.get("impressions", 0) for r in rules_perf),
        "clicks": sum(r.get("clicks", 0) for r in rules_perf),
        "favorites": await db.favorites.count_documents({}),
    }
    return {
        "totals": totals,
        "rules_performance": sorted(rules_perf, key=lambda x: x.get("impressions", 0), reverse=True)[:20],
        "favorites_by_category": fav_by_cat[:20],
    }


# ---------- Video Ad Rules ----------
class VideoAdRule(BaseModel):
    id: Optional[str] = None
    name: str
    category: str = "all"
    city: Optional[str] = ""
    video_url: str
    click_through_url: Optional[str] = ""
    advertiser_name: Optional[str] = ""
    cta_text: Optional[str] = "Learn more"
    skip_after_seconds: int = 5
    priority: int = 0
    enabled: bool = True


@api_router.post("/ad-config/video-rules")
async def add_video_rule(rule: VideoAdRule, _: bool = Depends(require_admin)):
    cfg = await db.app_config.find_one({"_id": "ad_config"})
    if cfg:
        cfg.pop("_id", None)
    else:
        cfg = dict(DEFAULT_AD_CONFIG)
    rules = (cfg.get("video_ad") or {}).get("rules") or []
    new_rule = rule.dict()
    new_rule["id"] = new_rule.get("id") or str(uuid.uuid4())
    rules.append(new_rule)
    cfg.setdefault("video_ad", dict(DEFAULT_AD_CONFIG["video_ad"]))
    cfg["video_ad"]["rules"] = rules
    cfg["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one({"_id": "ad_config"}, {"$set": cfg}, upsert=True)
    return new_rule


@api_router.put("/ad-config/video-rules/{rule_id}")
async def update_video_rule(rule_id: str, rule: VideoAdRule, _: bool = Depends(require_admin)):
    cfg = await db.app_config.find_one({"_id": "ad_config"})
    if not cfg:
        raise HTTPException(404, "Config not found")
    cfg.pop("_id", None)
    rules = (cfg.get("video_ad") or {}).get("rules") or []
    updated = rule.dict()
    updated["id"] = rule_id
    found = False
    for i, r in enumerate(rules):
        if r.get("id") == rule_id:
            rules[i] = updated
            found = True
            break
    if not found:
        raise HTTPException(404, "Rule not found")
    cfg["video_ad"]["rules"] = rules
    cfg["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one({"_id": "ad_config"}, {"$set": cfg}, upsert=True)
    return updated


@api_router.delete("/ad-config/video-rules/{rule_id}")
async def delete_video_rule(rule_id: str, _: bool = Depends(require_admin)):
    cfg = await db.app_config.find_one({"_id": "ad_config"})
    if not cfg:
        raise HTTPException(404, "Config not found")
    cfg.pop("_id", None)
    rules = (cfg.get("video_ad") or {}).get("rules") or []
    rules = [r for r in rules if r.get("id") != rule_id]
    cfg["video_ad"]["rules"] = rules
    cfg["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.app_config.update_one({"_id": "ad_config"}, {"$set": cfg}, upsert=True)
    return {"status": "ok"}


@api_router.get("/categories")
async def get_categories():
    """Public — returns categories from DB (seeded from defaults on first read)."""
    count = await db.categories.count_documents({})
    if count == 0:
        # Seed defaults with order preserved
        seeded = []
        for i, c in enumerate(DEFAULT_CATEGORIES):
            item = {**c, "order": i}
            seeded.append(item)
        if seeded:
            await db.categories.insert_many(seeded)
    docs = await db.categories.find({}, {"_id": 0}).sort("order", 1).to_list(500)
    return docs


class CategoryModel(BaseModel):
    key: str
    label: str
    icon: str = "pin"
    types: List[str] = []
    keyword: Optional[str] = None            # optional free-text query
    search_type: str = "type"                # "type" or "keyword"
    order: Optional[int] = 999


@api_router.post("/categories")
async def create_category(cat: CategoryModel, _: bool = Depends(require_admin)):
    if not cat.key or not cat.label or not cat.types:
        raise HTTPException(status_code=400, detail="key, label and types are required")
    existing = await db.categories.find_one({"key": cat.key})
    if existing:
        raise HTTPException(status_code=409, detail=f"Category with key '{cat.key}' already exists")
    if cat.order is None or cat.order == 999:
        last = await db.categories.find_one({}, sort=[("order", -1)])
        cat.order = (last.get("order", 0) + 1) if last else 0
    await db.categories.insert_one(cat.dict())
    return cat.dict()


@api_router.put("/categories/{key}")
async def update_category(key: str, cat: CategoryModel, _: bool = Depends(require_admin)):
    doc = await db.categories.find_one({"key": key})
    if not doc:
        raise HTTPException(status_code=404, detail="Category not found")
    if cat.key != key:
        # Key change requires uniqueness check
        clash = await db.categories.find_one({"key": cat.key})
        if clash:
            raise HTTPException(status_code=409, detail=f"Key '{cat.key}' already in use")
    await db.categories.update_one({"key": key}, {"$set": cat.dict()})
    return cat.dict()


@api_router.delete("/categories/{key}")
async def delete_category(key: str, _: bool = Depends(require_admin)):
    result = await db.categories.delete_one({"key": key})
    if result.deleted_count == 0:
        raise HTTPException(status_code=404, detail="Category not found")
    return {"status": "ok"}


@api_router.post("/categories/reset")
async def reset_categories(_: bool = Depends(require_admin)):
    """Reseed categories from defaults (destructive)."""
    await db.categories.delete_many({})
    seeded = [{**c, "order": i} for i, c in enumerate(DEFAULT_CATEGORIES)]
    if seeded:
        await db.categories.insert_many(seeded)
    docs = await db.categories.find({}, {"_id": 0}).sort("order", 1).to_list(500)
    return docs


class CategoryImportRow(BaseModel):
    key: str
    label: str
    icon: Optional[str] = "pin"
    types: str  # comma-separated in CSV


class CategoryImportPayload(BaseModel):
    rows: List[CategoryImportRow]
    mode: str = "merge"  # 'merge' (skip existing) | 'replace' (wipe first) | 'upsert'


@api_router.post("/categories/import")
async def import_categories(payload: CategoryImportPayload, _: bool = Depends(require_admin)):
    """Bulk-import categories from CSV rows (parsed on the client).
    - merge:   skip rows whose key already exists.
    - upsert:  update existing rows, insert new.
    - replace: wipe the collection first, then insert all rows.
    Returns counters + errors per row.
    """
    inserted = 0
    updated = 0
    skipped = 0
    errors: List[dict] = []

    if payload.mode == "replace":
        await db.categories.delete_many({})

    # Get max order for appending
    last = await db.categories.find_one({}, sort=[("order", -1)])
    next_order = (last.get("order", 0) + 1) if last else 0

    for idx, row in enumerate(payload.rows):
        try:
            key = (row.key or "").strip()
            label = (row.label or "").strip()
            types_raw = (row.types or "").strip()
            if not key or not label or not types_raw:
                errors.append({"row": idx, "error": "key, label and types are required"})
                continue
            types = [t.strip() for t in types_raw.split(",") if t.strip()]
            doc = {
                "key": key,
                "label": label,
                "icon": (row.icon or "pin").strip(),
                "types": types,
            }
            existing = await db.categories.find_one({"key": key})
            if existing:
                if payload.mode == "merge":
                    skipped += 1
                    continue
                # upsert or replace-with-existing (won't happen because we deleted)
                await db.categories.update_one({"key": key}, {"$set": doc})
                updated += 1
            else:
                doc["order"] = next_order
                next_order += 1
                await db.categories.insert_one(doc)
                inserted += 1
        except Exception as e:
            errors.append({"row": idx, "error": str(e)})

    total = await db.categories.count_documents({})
    return {
        "inserted": inserted,
        "updated": updated,
        "skipped": skipped,
        "errors": errors,
        "total_categories": total,
    }


# ---------- Pages (CMS) ----------
# Owner-managed CMS pages that can be pinned to the header or footer menu.
# Each page has a slug (URL-safe id), title, HTML/Markdown content and an
# optional menu placement. Only owner/editor can mutate — read is public.

import re as _re

_SLUG_RE = _re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")

# Slugs that would collide with existing top-level routes and must be blocked.
# Pages at /:slug — any slug in this set is reserved by the app itself.
_RESERVED_SLUGS = frozenset({
    "login", "register", "logout", "signup",
    "auth", "admin", "app", "api", "p",
    "settings", "profile", "dashboard",
    "assets", "static", "public", "favicon.ico",
})


def _slugify(s: str) -> str:
    s = (s or "").strip().lower()
    s = _re.sub(r"[^a-z0-9]+", "-", s).strip("-")
    return s or "page"


def _reject_reserved_slug(slug: str) -> None:
    if slug in _RESERVED_SLUGS:
        raise HTTPException(
            400,
            f"'{slug}' is a reserved route and cannot be used as a page slug. "
            "Try adding a suffix like '-page' or use a different name."
        )


class PageModel(BaseModel):
    slug: str
    title: str
    content: str = ""                              # markdown or html
    menu_location: str = "none"                    # 'header' | 'footer' | 'none'
    menu_label: Optional[str] = None               # override title for menu link
    order: int = 0
    published: bool = True


@api_router.get("/pages")
async def list_pages(location: Optional[str] = None, published_only: bool = False):
    """PUBLIC — used by the marketing site header/footer to render menu items.
    Filter by `location=header|footer` to get just menu entries."""
    q: dict = {}
    if location in ("header", "footer"):
        q["menu_location"] = location
    if published_only:
        q["published"] = True
    docs = await db.pages.find(q, {"_id": 0}).sort([("order", 1), ("title", 1)]).to_list(500)
    return docs


@api_router.get("/pages/{slug}")
async def get_page(slug: str):
    """PUBLIC — fetch a single page by slug. 404 if not found or unpublished."""
    doc = await db.pages.find_one({"slug": slug, "published": True}, {"_id": 0})
    if not doc:
        raise HTTPException(404, "Page not found")
    return doc


@api_router.post("/pages")
async def create_page(page: PageModel, _: bool = Depends(require_admin)):
    slug = _slugify(page.slug or page.title)
    _reject_reserved_slug(slug)
    if await db.pages.find_one({"slug": slug}):
        raise HTTPException(409, f"A page with slug '{slug}' already exists")
    if page.menu_location not in ("header", "footer", "none"):
        raise HTTPException(400, "menu_location must be 'header', 'footer' or 'none'")
    now = datetime.now(timezone.utc).isoformat()
    doc = page.dict()
    doc["slug"] = slug
    doc["created_at"] = now
    doc["updated_at"] = now
    await db.pages.insert_one(doc)
    doc.pop("_id", None)
    return doc


@api_router.put("/pages/{slug}")
async def update_page(slug: str, page: PageModel, _: bool = Depends(require_admin)):
    existing = await db.pages.find_one({"slug": slug})
    if not existing:
        raise HTTPException(404, "Page not found")
    new_slug = _slugify(page.slug or page.title)
    _reject_reserved_slug(new_slug)
    if new_slug != slug and await db.pages.find_one({"slug": new_slug}):
        raise HTTPException(409, f"A page with slug '{new_slug}' already exists")
    if page.menu_location not in ("header", "footer", "none"):
        raise HTTPException(400, "menu_location must be 'header', 'footer' or 'none'")
    patch = page.dict()
    patch["slug"] = new_slug
    patch["updated_at"] = datetime.now(timezone.utc).isoformat()
    await db.pages.update_one({"slug": slug}, {"$set": patch})
    return await db.pages.find_one({"slug": new_slug}, {"_id": 0})


@api_router.delete("/pages/{slug}")
async def delete_page(slug: str, _: bool = Depends(require_admin)):
    r = await db.pages.delete_one({"slug": slug})
    if r.deleted_count == 0:
        raise HTTPException(404, "Page not found")
    return {"status": "ok"}


# ---------- Weather ----------
@api_router.get("/weather")
async def weather(lat: float, lng: float, units: str = "metric"):
    """PUBLIC — mobile app fetches weather here. Uses OpenWeatherMap.
    Requires weather_api_key in Secrets (get from https://openweathermap.org/)."""
    key = await get_secret("weather_api_key")
    if not key:
        raise HTTPException(status_code=500, detail="Weather API key not configured. Set it in the admin Secrets vault.")
    url = "https://api.openweathermap.org/data/2.5/weather"
    params = {"lat": lat, "lon": lng, "appid": key, "units": units}
    async with httpx.AsyncClient(timeout=10.0) as cli:
        r = await cli.get(url, params=params)
    if r.status_code != 200:
        raise HTTPException(status_code=r.status_code, detail=_google_error_detail(r.text))
    d = r.json()
    return {
        "location": d.get("name"),
        "temp": (d.get("main") or {}).get("temp"),
        "feels_like": (d.get("main") or {}).get("feels_like"),
        "humidity": (d.get("main") or {}).get("humidity"),
        "wind_speed": (d.get("wind") or {}).get("speed"),
        "description": ((d.get("weather") or [{}])[0]).get("description"),
        "icon": ((d.get("weather") or [{}])[0]).get("icon"),
        "units": units,
    }


@api_router.get("/weather/forecast")
async def weather_forecast(lat: float, lng: float, units: str = "metric"):
    """PUBLIC — 5-day / 3-hour forecast via OpenWeatherMap."""
    key = await get_secret("weather_api_key")
    if not key:
        raise HTTPException(status_code=500, detail="Weather API key not configured")
    url = "https://api.openweathermap.org/data/2.5/forecast"
    params = {"lat": lat, "lon": lng, "appid": key, "units": units, "cnt": 8}
    async with httpx.AsyncClient(timeout=10.0) as cli:
        r = await cli.get(url, params=params)
    if r.status_code != 200:
        raise HTTPException(status_code=r.status_code, detail=_google_error_detail(r.text))
    d = r.json()
    return {
        "location": (d.get("city") or {}).get("name"),
        "units": units,
        "items": [
            {
                "at": it.get("dt_txt"),
                "temp": (it.get("main") or {}).get("temp"),
                "description": ((it.get("weather") or [{}])[0]).get("description"),
                "icon": ((it.get("weather") or [{}])[0]).get("icon"),
            }
            for it in d.get("list") or []
        ],
    }


# ---------- Default categories ----------
DEFAULT_CATEGORIES = [
    {"key": "airport", "label": "Airport", "icon": "airplane", "types": ["airport"]},
    {"key": "atm", "label": "ATM", "icon": "card", "types": ["atm"]},
    {"key": "bank", "label": "Bank", "icon": "business", "types": ["bank"]},
    {"key": "bar", "label": "Bar", "icon": "wine", "types": ["bar"]},
    {"key": "bookstore", "label": "Books", "icon": "book", "types": ["book_store"]},
    {"key": "bus", "label": "Bus", "icon": "bus", "types": ["bus_station"]},
    {"key": "cafe", "label": "Cafe", "icon": "cafe", "types": ["cafe"]},
    {"key": "car_rental", "label": "Car Rental", "icon": "car-sport", "types": ["car_rental"]},
    {"key": "car_repair", "label": "Car Service", "icon": "construct", "types": ["car_repair"]},
    {"key": "car_wash", "label": "Car Wash", "icon": "water", "types": ["car_wash"]},
    {"key": "church", "label": "Church", "icon": "home", "types": ["church"]},
    {"key": "clothing", "label": "Clothing", "icon": "shirt", "types": ["clothing_store"]},
    {"key": "coffee", "label": "Coffee", "icon": "cafe", "types": ["coffee_shop"]},
    {"key": "dentist", "label": "Dentist", "icon": "medkit", "types": ["dentist"]},
    {"key": "department_store", "label": "Dept. Store", "icon": "storefront", "types": ["department_store"]},
    {"key": "doctor", "label": "Doctor", "icon": "medical", "types": ["doctor"]},
    {"key": "electronics", "label": "Electronics", "icon": "phone-portrait", "types": ["electronics_store"]},
    {"key": "florist", "label": "Florist", "icon": "flower", "types": ["florist"]},
    {"key": "food", "label": "Food", "icon": "fast-food", "types": ["restaurant"]},
    {"key": "gas", "label": "Gas Station", "icon": "speedometer", "types": ["gas_station"]},
    {"key": "gym", "label": "Gym", "icon": "barbell", "types": ["gym"]},
    {"key": "hair_care", "label": "Hair Salon", "icon": "cut", "types": ["hair_care"]},
    {"key": "hardware", "label": "Hardware", "icon": "hammer", "types": ["hardware_store"]},
    {"key": "hospital", "label": "Hospital", "icon": "medkit", "types": ["hospital"]},
    {"key": "hotel", "label": "Hotel", "icon": "bed", "types": ["lodging"]},
    {"key": "jewelry", "label": "Jewelry", "icon": "diamond", "types": ["jewelry_store"]},
    {"key": "laundry", "label": "Laundry", "icon": "shirt-outline", "types": ["laundry"]},
    {"key": "library", "label": "Library", "icon": "library", "types": ["library"]},
    {"key": "liquor", "label": "Liquor", "icon": "wine", "types": ["liquor_store"]},
    {"key": "mosque", "label": "Mosque", "icon": "moon", "types": ["mosque"]},
    {"key": "movie", "label": "Movie Theater", "icon": "film", "types": ["movie_theater"]},
    {"key": "museum", "label": "Museum", "icon": "color-palette", "types": ["museum"]},
    {"key": "night_club", "label": "Night Club", "icon": "musical-notes", "types": ["night_club"]},
    {"key": "park", "label": "Park", "icon": "leaf", "types": ["park"]},
    {"key": "parking", "label": "Parking", "icon": "car", "types": ["parking"]},
    {"key": "pet_store", "label": "Pet Store", "icon": "paw", "types": ["pet_store"]},
    {"key": "pharmacy", "label": "Pharmacy", "icon": "medical", "types": ["pharmacy"]},
    {"key": "police", "label": "Police", "icon": "shield", "types": ["police"]},
    {"key": "post_office", "label": "Post Office", "icon": "mail", "types": ["post_office"]},
    {"key": "restaurant", "label": "Restaurant", "icon": "restaurant", "types": ["restaurant"]},
    {"key": "school", "label": "School", "icon": "school", "types": ["school"]},
    {"key": "shopping_mall", "label": "Shopping Mall", "icon": "bag", "types": ["shopping_mall"]},
    {"key": "spa", "label": "Spa", "icon": "rose", "types": ["spa"]},
    {"key": "stadium", "label": "Stadium", "icon": "football", "types": ["stadium"]},
    {"key": "supermarket", "label": "Supermarket", "icon": "cart", "types": ["supermarket"]},
    {"key": "synagogue", "label": "Synagogue", "icon": "star", "types": ["synagogue"]},
    {"key": "taxi", "label": "Taxi", "icon": "car", "types": ["taxi_stand"]},
    {"key": "temple", "label": "Temple", "icon": "flame", "types": ["hindu_temple"]},
    {"key": "train", "label": "Train", "icon": "train", "types": ["train_station"]},
    {"key": "transit", "label": "Transit", "icon": "bus", "types": ["transit_station"]},
    {"key": "veterinary", "label": "Veterinary", "icon": "paw", "types": ["veterinary_care"]},
    {"key": "zoo", "label": "Zoo", "icon": "leaf", "types": ["zoo"]},
]


app.include_router(api_router)
app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_origins=os.environ.get('CORS_ORIGINS', '*').split(','),
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.on_event("startup")
async def seed_owner_account():
    """Ensure a designated owner account exists on every boot.

    Reads `SEED_OWNER_EMAIL` and `SEED_OWNER_PASSWORD` from env. If either is
    missing this is a no-op. Safe to run repeatedly:
      - If the user does not exist  → creates it as owner with a bcrypt hash.
      - If the user exists          → sets role='owner' and updates the password
                                       hash so a redeploy can also serve as a
                                       password reset.

    This makes account recovery possible without shell access to production —
    just update the env vars and redeploy.
    """
    email = (os.environ.get('SEED_OWNER_EMAIL') or "").strip().lower()
    password = os.environ.get('SEED_OWNER_PASSWORD') or ""
    if not email or not password:
        return
    try:
        hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
        existing = await db.users.find_one({"email": email}, {"_id": 0})
        if existing:
            await db.users.update_one(
                {"email": email},
                {"$set": {"password_hash": hashed, "role": "owner"}},
            )
            await db.user_sessions.delete_many({"user_id": existing["user_id"]})
            logger.info(f"[seed_owner] refreshed owner account {email} (user_id={existing.get('user_id')})")
            return
        user_id = f"user_{uuid.uuid4().hex[:12]}"
        code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
        while await db.users.find_one({"referral_code": code}):
            code = py_secrets.token_urlsafe(6).replace("-", "").replace("_", "")[:8].upper()
        await db.users.insert_one({
            "user_id": user_id,
            "email": email,
            "name": (os.environ.get('SEED_OWNER_NAME') or email.split("@")[0]).strip(),
            "phone": "",
            "city": "",
            "role": "owner",
            "password_hash": hashed,
            "google_linked": False,
            "picture": None,
            "referral_code": code,
            "referred_by": None,
            "points": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        })
        logger.info(f"[seed_owner] created owner account {email} (user_id={user_id})")
    except Exception as e:
        logger.warning(f"[seed_owner] failed: {e}")


@app.on_event("shutdown")
async def shutdown_db_client():
    client.close()
