"""Public catalogue endpoints (read-only)."""
import re

from django.views.decorators.http import require_GET

from .db import get_db
from .utils import clean, err, ok, to_int

PUBLIC_PRODUCT_FIELDS = {
    "slug": 1, "name": 1, "brand": 1, "category": 1, "condition": 1, "price": 1,
    "compare_at": 1, "stock": 1, "images": 1, "specs": 1, "short": 1, "featured": 1,
    "warranty_months": 1, "updated_at": 1, "created_at": 1,
}

SORTS = {
    "newest": [("created_at", -1)],
    "price_asc": [("price", 1)],
    "price_desc": [("price", -1)],
    "popular": [("featured", -1), ("sold", -1), ("created_at", -1)],
}


@require_GET
def categories(request):
    db = get_db()
    cats = list(db.categories.find({"active": {"$ne": False}}, {"faqs": 0, "intro": 0}).sort("sort", 1))
    counts = {c["_id"]: c["n"] for c in db.products.aggregate([
        {"$match": {"active": True}},
        {"$group": {"_id": "$category", "n": {"$sum": 1}}},
    ])}
    out = []
    for c in cats:
        c = clean(c)
        c["count"] = counts.get(c["slug"], 0)
        out.append(c)
    return ok({"categories": out})


@require_GET
def category_detail(request, slug):
    cat = get_db().categories.find_one({"slug": slug, "active": {"$ne": False}})
    if not cat:
        return err("Category not found", 404)
    return ok({"category": clean(cat)})


@require_GET
def products(request):
    """GET /api/products?category=&brand=&condition=&q=&min=&max=&sort=&page=&limit=&featured=1"""
    db = get_db()
    q = {"active": True}
    g = request.GET
    if g.get("category"):
        q["category"] = g["category"]
    if g.get("brand"):
        q["brand"] = {"$regex": f"^{re.escape(g['brand'])}$", "$options": "i"}
    if g.get("condition") in ("new", "refurbished", "ex-uk"):
        q["condition"] = g["condition"]
    if g.get("featured") == "1":
        q["featured"] = True
    if g.get("in_stock") == "1":
        q["stock"] = {"$gt": 0}
    price = {}
    if g.get("min"):
        price["$gte"] = to_int(g["min"], 0, 0)
    if g.get("max"):
        price["$lte"] = to_int(g["max"], 10**9, 0)
    if price:
        q["price"] = price
    term = (g.get("q") or "").strip()[:80]
    if term:
        rx = {"$regex": re.escape(term), "$options": "i"}
        q["$or"] = [{"name": rx}, {"brand": rx}, {"specs.cpu": rx}, {"category": rx}]

    limit = to_int(g.get("limit"), 24, 1, 60)
    page = to_int(g.get("page"), 1, 1, 500)
    sort = SORTS.get(g.get("sort"), SORTS["popular"])
    total = db.products.count_documents(q)
    items = [clean(p) for p in db.products.find(q, PUBLIC_PRODUCT_FIELDS)
             .sort(sort).skip((page - 1) * limit).limit(limit)]

    # Facets for the filter sidebar (within the current category, ignoring other filters)
    base = {"active": True}
    if g.get("category"):
        base["category"] = g["category"]
    brands = sorted(b for b in db.products.distinct("brand", base) if b)

    return ok({
        "items": items, "total": total, "page": page, "limit": limit,
        "pages": max(1, -(-total // limit)), "brands": brands,
    })


@require_GET
def product_detail(request, slug):
    db = get_db()
    p = db.products.find_one({"slug": slug, "active": True}, {"cost": 0, "source_price": 0})
    if not p:
        return err("Product not found", 404)
    related = [clean(r) for r in db.products.find(
        {"category": p["category"], "active": True, "slug": {"$ne": slug}},
        PUBLIC_PRODUCT_FIELDS,
    ).sort([("featured", -1), ("created_at", -1)]).limit(4)]
    category = db.categories.find_one({"slug": p["category"]}, {"slug": 1, "name": 1})
    from . import seo_hubs
    hub = seo_hubs.model_for_product(p)
    model = None
    if hub:
        model = {"slug": hub["slug"], "name": hub["name"], "lo": hub["items"][0]["price"], "hi": hub["items"][-1]["price"],
                 "items": [seo_hubs.row(x) for x in hub["items"]]}
    from .reviews import summary
    return ok({"product": clean(p), "related": related, "category": clean(category), "model": model,
               "reviews": summary(slug), "updated": seo_hubs.month_year()})


@require_GET
def sitemap_data(request):
    """Slugs + lastmod for the frontend sitemap.xml."""
    db = get_db()
    prods = [{"slug": p["slug"], "updated_at": p.get("updated_at") or p.get("created_at"), "images": p.get("images", [])[:5]}
             for p in db.products.find({"active": True}, {"slug": 1, "updated_at": 1, "created_at": 1, "images": 1})]
    cats = [{"slug": c["slug"], "updated_at": c.get("updated_at")}
            for c in db.categories.find({"active": {"$ne": False}}, {"slug": 1, "updated_at": 1})]
    return ok({"products": prods, "categories": cats})


@require_GET
def health(request):
    get_db().command("ping")
    return ok({"status": "ok"})
