#!/usr/bin/env python3
"""Server-authoritative live auctions: soft-close, prayer extend, auto-bid."""

from __future__ import annotations

import json
import secrets
import time
from datetime import datetime, timezone
from typing import Any
from zoneinfo import ZoneInfo

DEFAULT_AUCTION_RULES = {
    "softCloseEnabled": True,
    "softCloseMinutes": 3,
    "softCloseExtendMinutes": 3,
    "prayerEnabled": True,
    "prayerExtendMinutes": 15,
    "prayerTimezone": "Asia/Dubai",
    "prayerWindows": [
        {"id": "fajr", "label": "Fajr", "start": "05:00", "end": "05:45"},
        {"id": "dhuhr", "label": "Dhuhr", "start": "12:15", "end": "12:45"},
        {"id": "asr", "label": "Asr", "start": "15:30", "end": "16:00"},
        {"id": "maghrib", "label": "Maghrib", "start": "17:45", "end": "18:15"},
        {"id": "isha", "label": "Isha", "start": "19:15", "end": "19:45"},
    ],
    "autoBidEnabled": True,
    "autoBidMinStep": 50,
    "livePollSeconds": 2,
    "serverAuthoritative": True,
    "fixedDurationDays": 7,
    "scheduleCloseHour": 18,
    "scheduleTimezone": "Asia/Dubai",
}


def ensure_auction_tables(conn) -> None:
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS live_auctions (
          id TEXT PRIMARY KEY,
          share_code TEXT,
          payload TEXT NOT NULL,
          current_bid REAL NOT NULL DEFAULT 0,
          starts_at TEXT,
          ends_at TEXT,
          updated REAL NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_live_auctions_code ON live_auctions(share_code);
        CREATE TABLE IF NOT EXISTS live_bids (
          id TEXT PRIMARY KEY,
          auction_id TEXT NOT NULL,
          bidder TEXT NOT NULL,
          email TEXT,
          amount REAL NOT NULL,
          at TEXT NOT NULL,
          created REAL NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_live_bids_auction ON live_bids(auction_id, created DESC);
        CREATE TABLE IF NOT EXISTS auto_bidders (
          auction_id TEXT NOT NULL,
          email TEXT NOT NULL,
          bidder TEXT,
          max_amount REAL NOT NULL,
          step REAL NOT NULL,
          active INTEGER NOT NULL DEFAULT 1,
          created REAL NOT NULL,
          PRIMARY KEY(auction_id, email)
        );
        CREATE TABLE IF NOT EXISTS auction_extensions (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          auction_id TEXT NOT NULL,
          reason TEXT NOT NULL,
          from_ends TEXT,
          to_ends TEXT,
          created REAL NOT NULL
        );
        """
    )


def normalize_auction_rules(raw: Any) -> dict:
    base = dict(DEFAULT_AUCTION_RULES)
    data = raw if isinstance(raw, dict) else {}
    base.update(data)
    windows = data.get("prayerWindows")
    if not isinstance(windows, list):
        windows = DEFAULT_AUCTION_RULES["prayerWindows"]
    clean_windows = []
    for i, w in enumerate(windows):
        if not isinstance(w, dict):
            continue
        start = str(w.get("start") or "").strip()
        end = str(w.get("end") or "").strip()
        if len(start) == 5 and len(end) == 5:
            clean_windows.append(
                {
                    "id": str(w.get("id") or f"w{i}"),
                    "label": str(w.get("label") or f"Window {i+1}")[:40],
                    "start": start,
                    "end": end,
                }
            )
    if not clean_windows:
        clean_windows = list(DEFAULT_AUCTION_RULES["prayerWindows"])

    def clamp_int(val, default, lo, hi):
        try:
            n = int(val)
        except (TypeError, ValueError):
            n = default
        return max(lo, min(hi, n))

    return {
        "softCloseEnabled": data.get("softCloseEnabled", True) is not False,
        "softCloseMinutes": clamp_int(base.get("softCloseMinutes"), 3, 1, 30),
        "softCloseExtendMinutes": clamp_int(base.get("softCloseExtendMinutes"), 3, 1, 30),
        "prayerEnabled": data.get("prayerEnabled", True) is not False,
        "prayerExtendMinutes": clamp_int(base.get("prayerExtendMinutes"), 15, 0, 120),
        "prayerTimezone": str(base.get("prayerTimezone") or "Asia/Dubai").strip() or "Asia/Dubai",
        "prayerWindows": clean_windows,
        "autoBidEnabled": data.get("autoBidEnabled", True) is not False,
        "autoBidMinStep": clamp_int(base.get("autoBidMinStep"), 50, 1, 100000),
        "livePollSeconds": clamp_int(base.get("livePollSeconds"), 2, 1, 15),
        "serverAuthoritative": data.get("serverAuthoritative", True) is not False,
        "fixedDurationDays": clamp_int(base.get("fixedDurationDays"), 7, 1, 30),
        "scheduleCloseHour": clamp_int(base.get("scheduleCloseHour"), 18, 0, 23),
        "scheduleTimezone": str(base.get("scheduleTimezone") or "Asia/Dubai").strip() or "Asia/Dubai",
    }


def _minutes(hhmm: str) -> int:
    try:
        h, m = hhmm.split(":")
        return int(h) * 60 + int(m)
    except Exception:
        return 0


def _clock_in_tz(ts: float, tz_name: str) -> str:
    try:
        tz = ZoneInfo(tz_name)
    except Exception:
        tz = timezone.utc
    dt = datetime.fromtimestamp(ts, tz=tz)
    return f"{dt.hour:02d}:{dt.minute:02d}"


def in_prayer_window(ts: float, rules: dict) -> bool:
    if not rules.get("prayerEnabled"):
        return False
    now_min = _minutes(_clock_in_tz(ts, rules.get("prayerTimezone") or "Asia/Dubai"))
    for w in rules.get("prayerWindows") or []:
        a = _minutes(str(w.get("start") or ""))
        b = _minutes(str(w.get("end") or ""))
        if a <= b:
            if a <= now_min <= b:
                return True
        elif now_min >= a or now_min <= b:
            return True
    return False


def parse_iso_ms(value: str | None) -> float:
    if not value:
        return float("nan")
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000.0
    except Exception:
        return float("nan")


def apply_extensions(ends_at: str | None, rules: dict, now_ms: float | None = None) -> tuple[str | None, list[str]]:
    if not ends_at:
        return ends_at, []
    now = time.time() * 1000.0 if now_ms is None else now_ms
    end_ms = parse_iso_ms(ends_at)
    if end_ms != end_ms:
        return ends_at, []
    reasons: list[str] = []
    out = end_ms
    if rules.get("softCloseEnabled"):
        left = out - now
        threshold = float(rules.get("softCloseMinutes") or 3) * 60_000.0
        extend = float(rules.get("softCloseExtendMinutes") or 3) * 60_000.0
        if 0 < left < threshold:
            nxt = max(out, now + extend)
            if nxt > out + 1:
                out = nxt
                reasons.append("soft_close")
    if rules.get("prayerEnabled") and float(rules.get("prayerExtendMinutes") or 0) > 0:
        bump = float(rules.get("prayerExtendMinutes") or 15) * 60_000.0
        if out > now and in_prayer_window(now / 1000.0, rules) and (out - now) <= bump * 2:
            nxt = max(out, now + bump)
            if nxt > out + 1:
                out = nxt
                reasons.append("prayer")
    if not reasons:
        return ends_at, []
    return datetime.fromtimestamp(out / 1000.0, tz=timezone.utc).isoformat().replace("+00:00", "Z"), reasons


def uid(prefix: str = "bid") -> str:
    return f"{prefix}_{secrets.token_hex(6)}"


def payload_from_row(row) -> dict:
    try:
        data = json.loads(row["payload"] or "{}")
    except Exception:
        data = {}
    if not isinstance(data, dict):
        data = {}
    data["id"] = row["id"]
    data["shareCode"] = row["share_code"] or data.get("shareCode") or ""
    data["currentBid"] = float(row["current_bid"] or data.get("currentBid") or 0)
    data["startsAt"] = row["starts_at"] or data.get("startsAt")
    data["endsAt"] = row["ends_at"] or data.get("endsAt")
    return data


def load_bids(conn, auction_id: str) -> list[dict]:
    rows = conn.execute(
        "SELECT id, bidder, email, amount, at FROM live_bids WHERE auction_id=? ORDER BY created DESC LIMIT 120",
        (auction_id,),
    ).fetchall()
    return [
        {
            "id": r["id"],
            "bidder": r["bidder"],
            "amount": float(r["amount"]),
            "at": r["at"],
            "email": r["email"] or "",
        }
        for r in rows
    ]


def load_auto_bidders(conn, auction_id: str) -> list[dict]:
    rows = conn.execute(
        "SELECT email, bidder, max_amount, step, created FROM auto_bidders WHERE auction_id=? AND active=1 ORDER BY created ASC",
        (auction_id,),
    ).fetchall()
    return [
        {
            "email": r["email"],
            "bidder": r["bidder"] or r["email"],
            "maxAmount": float(r["max_amount"]),
            "step": float(r["step"]),
            "created": float(r["created"] or 0),
        }
        for r in rows
    ]


def get_live_auction(conn, id_or_code: str) -> dict | None:
    key = str(id_or_code or "").strip()
    if not key:
        return None
    row = conn.execute("SELECT * FROM live_auctions WHERE id=?", (key,)).fetchone()
    if not row:
        row = conn.execute(
            "SELECT * FROM live_auctions WHERE upper(share_code)=?",
            (key.upper(),),
        ).fetchone()
    if not row:
        return None
    auction = payload_from_row(row)
    bids = load_bids(conn, row["id"])
    auction["bids"] = [{"id": b["id"], "bidder": b["bidder"], "amount": b["amount"], "at": b["at"]} for b in bids]
    if bids:
        auction["currentBid"] = max(float(auction.get("currentBid") or 0), float(bids[0]["amount"]))
    return auction


def save_auction_row(conn, auction: dict) -> None:
    aid = str(auction.get("id") or "").strip()
    conn.execute(
        "INSERT INTO live_auctions(id, share_code, payload, current_bid, starts_at, ends_at, updated) VALUES(?,?,?,?,?,?,?) "
        "ON CONFLICT(id) DO UPDATE SET share_code=excluded.share_code, payload=excluded.payload, current_bid=excluded.current_bid, "
        "starts_at=excluded.starts_at, ends_at=excluded.ends_at, updated=excluded.updated",
        (
            aid,
            str(auction.get("shareCode") or "").strip().upper(),
            json.dumps(auction, ensure_ascii=False),
            float(auction.get("currentBid") or 0),
            auction.get("startsAt"),
            auction.get("endsAt"),
            time.time(),
        ),
    )


def upsert_auction(conn, auction: dict, rules: dict) -> dict:
    aid = str(auction.get("id") or "").strip()
    if not aid:
        raise ValueError("id")
    existing = get_live_auction(conn, aid)
    if existing:
        merged = dict(existing)
        for k, v in auction.items():
            if k in ("bids",) and not v:
                continue
            if v is not None:
                merged[k] = v
        # Prefer higher bid / later end already on server.
        merged["currentBid"] = max(float(existing.get("currentBid") or 0), float(auction.get("currentBid") or 0))
        if existing.get("endsAt") and auction.get("endsAt"):
            if parse_iso_ms(existing["endsAt"]) > parse_iso_ms(str(auction["endsAt"])):
                merged["endsAt"] = existing["endsAt"]
        elif existing.get("endsAt"):
            merged["endsAt"] = existing["endsAt"]
        if existing.get("startsAt") and not merged.get("startsAt"):
            merged["startsAt"] = existing["startsAt"]
        if existing.get("bids") and not auction.get("bids"):
            merged["bids"] = existing["bids"]
        auction = merged
    ends, reasons = apply_extensions(auction.get("endsAt"), rules)
    if reasons and ends and ends != auction.get("endsAt"):
        for reason in reasons:
            conn.execute(
                "INSERT INTO auction_extensions(auction_id, reason, from_ends, to_ends, created) VALUES(?,?,?,?,?)",
                (aid, reason, auction.get("endsAt"), ends, time.time()),
            )
        auction["endsAt"] = ends
    if not auction.get("startsAt") and auction.get("durationHours") and auction.get("bids"):
        auction["startsAt"] = datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z")
    save_auction_row(conn, auction)
    if auction.get("bids"):
        for b in reversed(list(auction.get("bids") or [])[-40:]):
            bid_id = str(b.get("id") or uid("bid"))
            exists = conn.execute("SELECT id FROM live_bids WHERE id=?", (bid_id,)).fetchone()
            if exists:
                continue
            conn.execute(
                "INSERT INTO live_bids(id, auction_id, bidder, email, amount, at, created) VALUES(?,?,?,?,?,?,?)",
                (
                    bid_id,
                    aid,
                    str(b.get("bidder") or "Bidder")[:80],
                    str(b.get("email") or "").strip().lower()[:120],
                    float(b.get("amount") or 0),
                    str(b.get("at") or datetime.now(tz=timezone.utc).isoformat()),
                    time.time(),
                ),
            )
    return get_live_auction(conn, aid) or auction


def _append_bid(conn, auction: dict, amount: float, bidder: str, email: str, rules: dict) -> dict:
    aid = auction["id"]
    now_iso = datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z")
    now_ms = time.time() * 1000.0
    start_ms = parse_iso_ms(auction.get("startsAt"))
    if start_ms == start_ms and now_ms < start_ms:
        raise ValueError("not_open")
    ends = auction.get("endsAt")
    end_ms = parse_iso_ms(ends)
    if end_ms == end_ms and end_ms <= now_ms:
        raise ValueError("ended")
    current = float(auction.get("currentBid") or auction.get("startPrice") or 0)
    if amount <= current:
        raise ValueError("low")
    if not auction.get("startsAt") or not auction.get("endsAt"):
        raise ValueError("not_open")
    ends2, reasons = apply_extensions(auction.get("endsAt"), rules, now_ms)
    if reasons and ends2:
        for reason in reasons:
            conn.execute(
                "INSERT INTO auction_extensions(auction_id, reason, from_ends, to_ends, created) VALUES(?,?,?,?,?)",
                (aid, reason, auction.get("endsAt"), ends2, time.time()),
            )
        auction["endsAt"] = ends2
    bid_id = uid("bid")
    conn.execute(
        "INSERT INTO live_bids(id, auction_id, bidder, email, amount, at, created) VALUES(?,?,?,?,?,?,?)",
        (bid_id, aid, bidder[:80], email[:120], float(amount), now_iso, time.time()),
    )
    auction["currentBid"] = float(amount)
    parts = list(auction.get("participants") or [])
    if bidder and bidder not in parts:
        parts.append(bidder)
    auction["participants"] = parts
    auction["bids"] = [{"id": bid_id, "bidder": bidder, "amount": float(amount), "at": now_iso}] + list(auction.get("bids") or [])
    save_auction_row(conn, auction)
    return auction


def _leading_email(auction: dict) -> str:
    bids = auction.get("bids") or []
    if not bids:
        return ""
    return str(bids[0].get("email") or "").strip().lower()


def _run_auto_bids(conn, auction: dict, rules: dict, exclude_email: str = "") -> dict:
    if not rules.get("autoBidEnabled"):
        return auction
    min_step = float(rules.get("autoBidMinStep") or 50)
    guard = 0
    while guard < 40:
        guard += 1
        autos = load_auto_bidders(conn, auction["id"])
        current = float(auction.get("currentBid") or 0)
        leader = _leading_email(auction)
        # Prefer bids table email when present on latest row.
        if not leader:
            row = conn.execute(
                "SELECT email FROM live_bids WHERE auction_id=? ORDER BY created DESC LIMIT 1",
                (auction["id"],),
            ).fetchone()
            leader = str((row["email"] if row else "") or "").strip().lower()
        contenders = []
        for a in autos:
            email = str(a["email"] or "").lower()
            if exclude_email and email == exclude_email.lower():
                continue
            if leader and email == leader:
                continue  # already winning — do not bid against self
            step = max(min_step, float(a.get("step") or min_step))
            nxt = current + step
            if nxt <= float(a["maxAmount"]) + 1e-9 and nxt > current:
                contenders.append((float(a.get("created") or 0), a, nxt, step))
        if not contenders:
            break
        contenders.sort(key=lambda x: (x[2], x[0]))
        target_amount = contenders[0][2]
        winner = None
        for a in autos:
            email = str(a["email"] or "").lower()
            if exclude_email and email == exclude_email.lower():
                continue
            if leader and email == leader:
                continue
            step = max(min_step, float(a.get("step") or min_step))
            if current + step <= float(a["maxAmount"]) + 1e-9 and abs((current + step) - target_amount) < 1e-6:
                winner = (a, current + step)
                break
        if not winner:
            break
        a, amount = winner
        auction = _append_bid(
            conn,
            auction,
            amount,
            str(a.get("bidder") or a["email"]),
            str(a["email"]),
            rules,
        )
    return auction


def place_bid(conn, auction_id: str, amount: float, bidder: str, email: str, rules: dict) -> dict:
    auction = get_live_auction(conn, auction_id)
    if not auction:
        raise ValueError("missing")
    auction = _append_bid(conn, auction, float(amount), bidder or "Bidder", (email or "").strip().lower(), rules)
    auction = _run_auto_bids(conn, auction, rules, exclude_email=(email or "").strip().lower())
    return get_live_auction(conn, auction["id"]) or auction


def set_auto_bid(conn, auction_id: str, email: str, max_amount: float, step: float, bidder: str, rules: dict) -> dict:
    if not rules.get("autoBidEnabled"):
        raise ValueError("disabled")
    auction = get_live_auction(conn, auction_id)
    if not auction:
        raise ValueError("missing")
    email_n = email.strip().lower()
    if not email_n or "@" not in email_n:
        raise ValueError("email")
    min_step = float(rules.get("autoBidMinStep") or 50)
    step = max(min_step, float(step or min_step))
    max_amount = float(max_amount)
    current = float(auction.get("currentBid") or 0)
    if max_amount <= current:
        raise ValueError("low")
    conn.execute(
        "INSERT INTO auto_bidders(auction_id, email, bidder, max_amount, step, active, created) VALUES(?,?,?,?,?,1,?) "
        "ON CONFLICT(auction_id, email) DO UPDATE SET bidder=excluded.bidder, max_amount=excluded.max_amount, step=excluded.step, active=1",
        (auction["id"], email_n, (bidder or email_n)[:80], max_amount, step, time.time()),
    )
    # If someone else is leading below our max, fire once.
    auction = _run_auto_bids(conn, auction, rules, exclude_email="")
    return get_live_auction(conn, auction["id"]) or auction


def clear_auto_bid(conn, auction_id: str, email: str) -> dict:
    auction = get_live_auction(conn, auction_id)
    if not auction:
        raise ValueError("missing")
    conn.execute(
        "UPDATE auto_bidders SET active=0 WHERE auction_id=? AND email=?",
        (auction["id"], email.strip().lower()),
    )
    return get_live_auction(conn, auction["id"]) or auction


def live_state(conn, auction_id: str, rules: dict) -> dict:
    auction = get_live_auction(conn, auction_id)
    if not auction:
        raise ValueError("missing")
    # Refresh prayer/soft-close while polling if still live.
    ends, reasons = apply_extensions(auction.get("endsAt"), rules)
    if reasons and ends and ends != auction.get("endsAt"):
        for reason in reasons:
            conn.execute(
                "INSERT INTO auction_extensions(auction_id, reason, from_ends, to_ends, created) VALUES(?,?,?,?,?)",
                (auction["id"], f"poll_{reason}", auction.get("endsAt"), ends, time.time()),
            )
        auction["endsAt"] = ends
        save_auction_row(conn, auction)
    return {
        "ok": True,
        "auction": auction,
        "autoBids": load_auto_bidders(conn, auction["id"]),
        "serverTime": datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z"),
        "rules": rules,
    }


def auction_phase(auction: dict, now_ms: float | None = None) -> str:
    now = time.time() * 1000.0 if now_ms is None else float(now_ms)
    review = str(auction.get("reviewStatus") or "live")
    if review == "rejected":
        return "ended"
    if review == "pending":
        return "waiting"
    start_ms = parse_iso_ms(auction.get("startsAt"))
    end_ms = parse_iso_ms(auction.get("endsAt"))
    if end_ms != end_ms:
        return "waiting"
    if start_ms == start_ms and now < start_ms:
        return "waiting"
    if not (start_ms == start_ms) and auction.get("durationHours") and not auction.get("startsAt"):
        return "waiting"
    return "live" if end_ms > now else "ended"


def load_extensions(conn, auction_id: str, limit: int = 40) -> list[dict]:
    rows = conn.execute(
        "SELECT reason, from_ends, to_ends, created FROM auction_extensions WHERE auction_id=? ORDER BY id DESC LIMIT ?",
        (auction_id, int(limit)),
    ).fetchall()
    return [
        {
            "reason": r["reason"],
            "fromEnds": r["from_ends"],
            "toEnds": r["to_ends"],
            "created": float(r["created"] or 0),
        }
        for r in rows
    ]


def _admin_winner(conn, auction_id: str, bids: list[dict] | None = None) -> dict | None:
    rows = bids
    if rows is None:
        rows = load_bids(conn, auction_id)
    if not rows:
        return None
    top = rows[0]
    return {
        "bidder": top.get("bidder") or "",
        "email": top.get("email") or "",
        "amount": float(top.get("amount") or 0),
        "at": top.get("at") or "",
    }


def _wait_reason(auction: dict, phase: str, start_ms: float) -> str:
    review = str(auction.get("reviewStatus") or "live")
    if review == "rejected":
        return "rejected"
    if phase != "waiting":
        return ""
    if review == "pending":
        return "pending_review"
    if not (start_ms == start_ms):
        return "missing_schedule"
    return "scheduled"


def _admin_summary(conn, auction: dict, now_ms: float) -> dict:
    aid = str(auction.get("id") or "")
    bids = load_bids(conn, aid)
    auto_bids = load_auto_bidders(conn, aid)
    unique_emails = {str(b.get("email") or "").strip().lower() for b in bids if str(b.get("email") or "").strip()}
    unique_names = {str(b.get("bidder") or "").strip() for b in bids if str(b.get("bidder") or "").strip()}
    unique_bidders = len(unique_emails) if unique_emails else len(unique_names)
    phase = auction_phase(auction, now_ms)
    start_ms = parse_iso_ms(auction.get("startsAt"))
    end_ms = parse_iso_ms(auction.get("endsAt"))
    remaining = None
    opens_in = None
    if phase == "live" and end_ms == end_ms:
        remaining = max(0, int(end_ms - now_ms))
    if phase == "waiting" and start_ms == start_ms:
        opens_in = max(0, int(start_ms - now_ms))
    participants = list(auction.get("participants") or [])
    winner = _admin_winner(conn, aid, bids) if phase == "ended" else None
    leader = _admin_winner(conn, aid, bids) if bids else None
    return {
        "id": aid,
        "shareCode": auction.get("shareCode") or "",
        "title": auction.get("title") or "",
        "seller": auction.get("seller") or "",
        "sellerEmail": auction.get("sellerEmail") or "",
        "reviewStatus": auction.get("reviewStatus") or "live",
        "waitReason": _wait_reason(auction, phase, start_ms),
        "currency": auction.get("currency") or "AED",
        "startPrice": float(auction.get("startPrice") or 0),
        "currentBid": float(auction.get("currentBid") or (bids[0]["amount"] if bids else 0) or 0),
        "bidStep": float(auction.get("bidStep") or 0),
        "startsAt": auction.get("startsAt") or "",
        "endsAt": auction.get("endsAt") or "",
        "durationHours": float(auction.get("durationHours") or 0) or None,
        "phase": phase,
        "bidCount": len(bids),
        "uniqueBidders": unique_bidders,
        "participantCount": len(participants),
        "participants": participants[:40],
        "autoBidCount": len(auto_bids),
        "leader": leader,
        "winner": winner,
        "remainingMs": remaining,
        "opensInMs": opens_in,
        "breed": auction.get("breed") or "",
        "sex": auction.get("sex") or "",
        "ring": auction.get("ring") or "",
        "countryCode": auction.get("countryCode") or "",
        "serial": auction.get("serial") or "",
        "updated": float(auction.get("updated") or 0),
        "latestBidAt": (bids[0].get("at") if bids else None),
    }


def _public_review_ok(auction: dict) -> bool:
    status = str(auction.get("reviewStatus") or "live").strip().lower()
    return status in ("", "live")


def _public_auction_card(auction: dict) -> dict:
    """Slim shareable auction for the public feed (no seller emails in bids)."""
    photos = [str(p) for p in (auction.get("photos") or []) if isinstance(p, str)][:6]
    # Drop device-local paths that cannot play for other viewers.
    video = str(auction.get("videoUrl") or "")
    if video.startswith(("file:", "blob:", "content:")):
        video = ""
    bids = [
        {
            "id": b.get("id"),
            "bidder": b.get("bidder"),
            "amount": float(b.get("amount") or 0),
            "at": b.get("at"),
        }
        for b in (auction.get("bids") or [])[:40]
        if isinstance(b, dict)
    ]
    return {
        "id": auction.get("id"),
        "title": auction.get("title") or "",
        "seller": auction.get("seller") or "",
        "sellerEmail": auction.get("sellerEmail") or "",
        "reviewStatus": auction.get("reviewStatus") or "live",
        "startPrice": float(auction.get("startPrice") or 0),
        "currentBid": float(auction.get("currentBid") or 0),
        "bidStep": auction.get("bidStep"),
        "currency": auction.get("currency") or "EGP",
        "durationHours": auction.get("durationHours"),
        "startsAt": auction.get("startsAt"),
        "endsAt": auction.get("endsAt"),
        "bids": bids,
        "shareCode": auction.get("shareCode") or "",
        "participants": list(auction.get("participants") or [])[:80],
        "photos": photos,
        "serial": auction.get("serial"),
        "year": auction.get("year"),
        "breed": auction.get("breed"),
        "strain": auction.get("strain"),
        "sex": auction.get("sex"),
        "color": auction.get("color"),
        "ring": auction.get("ring"),
        "origin": auction.get("origin"),
        "notes": auction.get("notes"),
        "videoUrl": video,
        "reach": auction.get("reach") or "worldwide",
        "countryCode": auction.get("countryCode") or "",
        "category": auction.get("category"),
        "extras": auction.get("extras") if isinstance(auction.get("extras"), dict) else {},
    }


def list_auctions_public(conn, *, limit: int = 80) -> dict:
    """Public board: approved/live lots only (pending stays private to the seller)."""
    now_ms = time.time() * 1000.0
    rows = conn.execute(
        "SELECT * FROM live_auctions ORDER BY updated DESC LIMIT ?",
        (max(1, min(int(limit or 80), 200)),),
    ).fetchall()
    active = []
    ended = []
    for row in rows:
        auction = payload_from_row(row)
        if not _public_review_ok(auction):
            continue
        # Attach recent bids for the card.
        bids = load_bids(conn, row["id"])
        auction["bids"] = [
            {"id": b["id"], "bidder": b["bidder"], "amount": b["amount"], "at": b["at"]} for b in bids
        ]
        if bids:
            auction["currentBid"] = max(float(auction.get("currentBid") or 0), float(bids[0]["amount"]))
        card = _public_auction_card(auction)
        phase = auction_phase(auction, now_ms)
        if phase == "ended":
            ended.append(card)
        else:
            active.append(card)
    return {
        "ok": True,
        "serverTime": datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z"),
        "auctions": active + ended,
    }


def list_auctions_admin(
    conn,
    *,
    status: str = "all",
    query: str = "",
    limit: int = 200,
) -> dict:
    now_ms = time.time() * 1000.0
    rows = conn.execute(
        "SELECT * FROM live_auctions ORDER BY updated DESC LIMIT ?",
        (max(1, min(int(limit or 200), 500)),),
    ).fetchall()
    items = []
    q = str(query or "").strip().lower()
    want = str(status or "all").strip().lower()
    if want not in ("all", "live", "waiting", "ended", "active", "pending_review", "rejected"):
        want = "all"
    for row in rows:
        auction = payload_from_row(row)
        auction["updated"] = float(row["updated"] or 0)
        summary = _admin_summary(conn, auction, now_ms)
        phase = summary["phase"]
        wait_reason = str(summary.get("waitReason") or "")
        review = str(summary.get("reviewStatus") or "live")
        if want == "active" and phase == "ended":
            continue
        if want == "pending_review" and wait_reason != "pending_review" and review != "pending":
            continue
        if want == "rejected" and review != "rejected" and wait_reason != "rejected":
            continue
        if want in ("live", "waiting", "ended") and phase != want:
            continue
        if q:
            blob = " ".join(
                [
                    str(summary.get("title") or ""),
                    str(summary.get("seller") or ""),
                    str(summary.get("sellerEmail") or ""),
                    str(summary.get("shareCode") or ""),
                    str(summary.get("id") or ""),
                    str(summary.get("ring") or ""),
                    str(summary.get("serial") or ""),
                    str((summary.get("leader") or {}).get("bidder") or ""),
                    str((summary.get("winner") or {}).get("bidder") or ""),
                ]
            ).lower()
            if q not in blob:
                continue
        items.append(summary)

    counts = {"all": 0, "live": 0, "waiting": 0, "ended": 0, "pending_review": 0, "rejected": 0}
    # Full counts across DB (not only filtered page).
    all_rows = conn.execute("SELECT * FROM live_auctions").fetchall()
    for row in all_rows:
        auction = payload_from_row(row)
        phase = auction_phase(auction, now_ms)
        review = str(auction.get("reviewStatus") or "live")
        counts["all"] += 1
        counts[phase] = counts.get(phase, 0) + 1
        if review == "pending":
            counts["pending_review"] = counts.get("pending_review", 0) + 1
        if review == "rejected":
            counts["rejected"] = counts.get("rejected", 0) + 1

    bid_today = conn.execute(
        "SELECT COUNT(*) n FROM live_bids WHERE created>=?",
        (time.time() - 86400,),
    ).fetchone()["n"]
    unique_today = conn.execute(
        """
        SELECT COUNT(DISTINCT lower(COALESCE(NULLIF(email,''), bidder))) n
        FROM live_bids WHERE created>=?
        """,
        (time.time() - 86400,),
    ).fetchone()["n"]
    live_volume = 0.0
    for row in all_rows:
        auction = payload_from_row(row)
        if auction_phase(auction, now_ms) == "live":
            live_volume += float(auction.get("currentBid") or 0)

    return {
        "ok": True,
        "serverTime": datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z"),
        "counts": counts,
        "stats": {
            "bidsToday": int(bid_today or 0),
            "uniqueBiddersToday": int(unique_today or 0),
            "liveVolume": live_volume,
            "active": int(counts.get("live", 0) + counts.get("waiting", 0)),
        },
        "auctions": items,
    }


def admin_auction_detail(conn, auction_id: str, rules: dict) -> dict:
    state = live_state(conn, auction_id, rules)
    auction = state["auction"]
    aid = auction["id"]
    now_ms = time.time() * 1000.0
    bids = load_bids(conn, aid)  # includes emails for admin
    summary = _admin_summary(conn, auction, now_ms)
    auction_out = dict(auction)
    auction_out["bids"] = [
        {
            "id": b["id"],
            "bidder": b["bidder"],
            "email": b.get("email") or "",
            "amount": float(b["amount"]),
            "at": b["at"],
        }
        for b in bids
    ]
    return {
        "ok": True,
        "serverTime": state["serverTime"],
        "rules": rules,
        "summary": summary,
        "auction": auction_out,
        "autoBids": state["autoBids"],
        "extensions": load_extensions(conn, aid),
        "photos": list(auction.get("photos") or [])[:8],
        "videoUrl": auction.get("videoUrl") or "",
        "notes": auction.get("notes") or "",
        "extras": auction.get("extras") or {},
    }


def _iso_utc(dt: datetime) -> str:
    return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")


def schedule_auction_window(rules: dict | None = None, *, days: int | None = None, now_ms: float | None = None) -> dict:
    """Mirror client scheduleAuctionWindow: next close-hour start, then +days at same hour."""
    r = normalize_auction_rules(rules or {})
    day_count = max(1, min(30, int(days or r.get("fixedDurationDays") or 7)))
    hour = max(0, min(23, int(r.get("scheduleCloseHour") if r.get("scheduleCloseHour") is not None else 18)))
    tz_name = str(r.get("scheduleTimezone") or "Asia/Dubai").strip() or "Asia/Dubai"
    try:
        tz = ZoneInfo(tz_name)
    except Exception:
        tz = ZoneInfo("Asia/Dubai")
        tz_name = "Asia/Dubai"
    now = datetime.now(tz=timezone.utc) if now_ms is None else datetime.fromtimestamp(now_ms / 1000.0, tz=timezone.utc)
    local_now = now.astimezone(tz)
    start_local = local_now.replace(hour=hour, minute=0, second=0, microsecond=0)
    if local_now >= start_local:
        from datetime import timedelta

        start_local = start_local + timedelta(days=1)
    from datetime import timedelta

    end_local = start_local + timedelta(days=day_count)
    return {
        "startsAt": _iso_utc(start_local),
        "endsAt": _iso_utc(end_local),
        "durationHours": day_count * 24,
        "scheduleHour": hour,
        "scheduleTimezone": tz_name,
        "days": day_count,
    }


def _normalize_iso(value: Any) -> str:
    raw = str(value or "").strip()
    if not raw:
        return ""
    ms = parse_iso_ms(raw)
    if not (ms == ms):
        raise ValueError("bad_time")
    return _iso_utc(datetime.fromtimestamp(ms / 1000.0, tz=timezone.utc))


def admin_update_auction(conn, auction_id: str, body: dict, rules: dict) -> dict:
    """Admin controls: approve, set schedule, extend, force end."""
    auction = get_live_auction(conn, auction_id)
    if not auction:
        raise ValueError("missing")
    action = str((body or {}).get("action") or "set_schedule").strip().lower()
    now_iso = _iso_utc(datetime.now(tz=timezone.utc))

    if action in ("approve", "go_live"):
        auction["reviewStatus"] = "live"
        starts = str(body.get("startsAt") or auction.get("startsAt") or "").strip()
        ends = str(body.get("endsAt") or auction.get("endsAt") or "").strip()
        if not starts or not ends or not (parse_iso_ms(ends) == parse_iso_ms(ends)):
            days = None
            if body.get("days") is not None:
                try:
                    days = int(body.get("days"))
                except Exception:
                    days = None
            elif auction.get("durationHours"):
                try:
                    days = max(1, int(round(float(auction.get("durationHours")) / 24)))
                except Exception:
                    days = None
            window = schedule_auction_window(rules, days=days)
            starts = starts or window["startsAt"]
            ends = ends if ends and parse_iso_ms(ends) == parse_iso_ms(ends) else window["endsAt"]
            auction["durationHours"] = window["durationHours"]
        auction["startsAt"] = _normalize_iso(starts)
        auction["endsAt"] = _normalize_iso(ends)
        if parse_iso_ms(auction["endsAt"]) <= parse_iso_ms(auction["startsAt"]):
            raise ValueError("bad_window")

    elif action == "set_schedule":
        starts = _normalize_iso(body.get("startsAt") or auction.get("startsAt"))
        ends = _normalize_iso(body.get("endsAt") or auction.get("endsAt"))
        if not starts or not ends:
            raise ValueError("schedule")
        if parse_iso_ms(ends) <= parse_iso_ms(starts):
            raise ValueError("bad_window")
        auction["startsAt"] = starts
        auction["endsAt"] = ends
        if "reviewStatus" in body:
            review = str(body.get("reviewStatus") or "").strip().lower()
            if review in ("live", "pending", "rejected"):
                auction["reviewStatus"] = review

    elif action == "extend":
        try:
            minutes = max(1, min(7 * 24 * 60, int(body.get("minutes") or 60)))
        except Exception:
            minutes = 60
        end_ms = parse_iso_ms(auction.get("endsAt"))
        base = end_ms if end_ms == end_ms else time.time() * 1000.0
        new_end = _iso_utc(datetime.fromtimestamp((base + minutes * 60_000) / 1000.0, tz=timezone.utc))
        conn.execute(
            "INSERT INTO auction_extensions(auction_id, reason, from_ends, to_ends, created) VALUES(?,?,?,?,?)",
            (auction["id"], f"admin_extend_{minutes}m", auction.get("endsAt"), new_end, time.time()),
        )
        auction["endsAt"] = new_end
        if str(auction.get("reviewStatus") or "") == "pending":
            auction["reviewStatus"] = "live"
        if not auction.get("startsAt"):
            auction["startsAt"] = now_iso

    elif action in ("force_end", "end_now"):
        prev = auction.get("endsAt")
        auction["endsAt"] = now_iso
        if not auction.get("startsAt"):
            auction["startsAt"] = now_iso
        auction["reviewStatus"] = "live"
        conn.execute(
            "INSERT INTO auction_extensions(auction_id, reason, from_ends, to_ends, created) VALUES(?,?,?,?,?)",
            (auction["id"], "admin_force_end", prev, now_iso, time.time()),
        )

    elif action == "set_review":
        review = str(body.get("reviewStatus") or "").strip().lower()
        if review not in ("live", "pending", "rejected"):
            raise ValueError("review")
        auction["reviewStatus"] = review

    elif action in ("reject", "deny"):
        auction["reviewStatus"] = "rejected"
        if not auction.get("startsAt"):
            auction["startsAt"] = now_iso
        prev = auction.get("endsAt")
        auction["endsAt"] = now_iso
        conn.execute(
            "INSERT INTO auction_extensions(auction_id, reason, from_ends, to_ends, created) VALUES(?,?,?,?,?)",
            (auction["id"], "admin_reject", prev, now_iso, time.time()),
        )

    else:
        raise ValueError("action")

    save_auction_row(conn, auction)
    return admin_auction_detail(conn, auction["id"], rules)
