"""SEO landing pages generated from live catalogue data.

- Model hubs (/models/<slug>): every variant of one model with a price table ("HP EliteBook 840 G5 price in Kenya").
- Collections (/shop/<slug>): brand, budget and use-case landing pages ("HP laptops price in Kenya",
  "laptops under 30,000", "best laptops for students").
- Laptop price list (/laptop-prices-kenya): a dated, complete price table.

All text is computed from current products and prices on each request (cached briefly), so figures are
always correct and pages refresh themselves as stock changes.
"""
import re
import time
from collections import defaultdict
from datetime import datetime
from zoneinfo import ZoneInfo

from django.conf import settings

from .db import get_db
from .utils import slugify

LAPTOP_CATS = ("refurbished-laptops", "new-laptops", "gaming-laptops")
COMPUTER_CATS = LAPTOP_CATS + ("desktops",)
FIELDS = {"slug": 1, "name": 1, "brand": 1, "category": 1, "condition": 1, "price": 1, "compare_at": 1, "stock": 1,
          "specs": 1, "images": 1, "warranty_months": 1, "updated_at": 1, "featured": 1}
_cache = {"t": 0, "items": None}


def products():
    if _cache["items"] is None or time.time() - _cache["t"] > 60:
        _cache["items"] = list(get_db().products.find({"active": True}, FIELDS))
        for p in _cache["items"]:
            p["_id"] = str(p["_id"])
        _cache["t"] = time.time()
    return _cache["items"]


def ksh(n):
    return f"KES {int(n):,}"


def month_year():
    return datetime.now(ZoneInfo("Africa/Nairobi")).strftime("%B %Y")


def site():
    return settings.SITE_NAME


# ------------------------------------------------------------------ model grouping

MODEL_PATTERNS = [
    r"EliteBook\s+(?:x360\s+)?\d{3,4}\s*G\d", r"ZBook\s+(?:Power|Firefly)\s+\d{2}", r"\bOmen\b", r"\bVictus\b",
    r"\bSpectre\b", r"Latitude\s+[eE]?\d{4}", r"XPS\s+13", r"Alienware", r"OptiPlex", r"X1\s+(?:Carbon|Yoga)",
    r"ThinkPad\s+[TXE]\d{2,3}s?", r"Yoga\s+\d+e?", r"IdeaPad[- ]\d", r"ThinkBook\s+1\d", r"Legion", r"\b250\s*G\d+",
    r"ProDesk\s+\d{3}\s*G\d", r"ExpertBook\s+B\d", r"All in One",
]
CANON = {"elitebook": "EliteBook", "zbook": "ZBook", "thinkpad": "ThinkPad", "ideapad": "IdeaPad", "thinkbook": "ThinkBook",
         "expertbook": "ExpertBook", "x360": "x360", "xps": "XPS", "optiplex": "OptiPlex", "prodesk": "ProDesk",
         "all in one": "All-in-One", "omen": "Omen", "victus": "Victus", "spectre": "Spectre x360", "legion": "Legion",
         "alienware": "Alienware", "latitude": "Latitude", "carbon": "Carbon", "yoga": "Yoga", "power": "Power",
         "firefly": "Firefly"}


def _canon(s):
    s = re.sub(r"\s+", " ", s.replace("-", " ")).strip()
    s = re.sub(r"(?i)(\d{3,4})\s*(g\d+)", lambda m: f"{m.group(1)} {m.group(2).upper()}", s)
    s = re.sub(r"(?i)\b([a-z]?\d{4})\b", lambda m: m.group(1).upper(), s)
    out = []
    for w in s.split(" "):
        out.append(CANON.get(w.lower(), w))
    s = " ".join(out)
    return s.replace("All in One", "All-in-One")


def model_of(p):
    """Return (model_name, kind) or (None, None)."""
    n = p["name"]
    cat = p["category"]
    if cat in COMPUTER_CATS:
        for pt in MODEL_PATTERNS:
            m = re.search(pt, n, re.I)
            if m:
                core = _canon(m.group(0))
                brand = {"Alienware": "Dell"}.get(p["brand"], p["brand"])
                core = re.sub(r"^x1", "X1", core)
                if core.startswith(("X1", "ThinkPad")) and brand == "Lenovo" and not core.startswith("ThinkPad"):
                    core = "ThinkPad " + core
                if core.startswith("Alienware"):
                    return "Alienware Gaming Laptop", "laptop"
                if core == "250 G9" or core.startswith("250 G"):
                    core = core.replace(" ", " ")
                return f"{brand} {core}".replace("HP HP", "HP"), ("desktop" if cat == "desktops" else "laptop")
        return None, None
    if cat == "ram":
        cap = re.search(r"(\d+)\s*GB", n, re.I)
        if not cap:
            return None, None
        gen = "DDR3" if re.search(r"ddr3|1333|1600", n, re.I) else "DDR4"
        form = "Laptop" if "laptop" in n.lower() else "Desktop"
        return f"{cap.group(1)}GB {gen} {form} RAM", "ram"
    if cat == "storage":
        cap = re.search(r"(\d+)\s*(GB|TB)", n, re.I)
        if not cap:
            return None, None
        c = (cap.group(1) + cap.group(2).upper()).replace("1000GB", "1TB")
        low = n.lower()
        kind = ("mSATA SSD" if "msata" in low else "M.2 NVMe SSD" if "nvme" in low else "M.2 SSD" if re.search(r"m\.?2", low)
                else "2.5-inch SSD" if "ssd" in low else "Hard Disk")
        return f"{c} {kind}", "storage"
    return None, None


def model_groups():
    g = defaultdict(list)
    for p in products():
        m, kind = model_of(p)
        if m:
            g[m].append(p)
    return {slugify(k): {"name": k, "items": sorted(v, key=lambda x: x["price"]), "kind": model_of(v[0])[1]}
            for k, v in g.items() if len(v) >= 2}


def model_for_product(p):
    m, _ = model_of(p)
    if not m:
        return None
    groups = model_groups()
    return groups.get(slugify(m)) and {"slug": slugify(m), **groups[slugify(m)]}


def row(p):
    s = p.get("specs") or {}
    return {"slug": p["slug"], "name": p["name"], "price": p["price"], "compare_at": p.get("compare_at") or 0,
            "condition": p["condition"], "cpu": s.get("cpu", ""), "ram": s.get("ram", ""), "storage": s.get("storage", ""),
            "gpu": s.get("gpu", ""), "display": s.get("display", ""), "stock": p.get("stock", 0),
            "images": p.get("images", []), "brand": p["brand"], "category": p["category"],
            "warranty_months": p.get("warranty_months", 0), "specs": s}


def model_page(slug):
    g = model_groups().get(slug)
    if not g:
        return None
    items, name, kind = g["items"], g["name"], g["kind"]
    lo, hi = items[0]["price"], items[-1]["price"]
    conds = sorted({x["condition"] for x in items})
    n = len(items)
    S = site()
    my = month_year()
    cheapest = items[0]
    best = max(items, key=lambda x: (_spec_score(x) / max(x["price"], 1), -x["price"]))
    answer = (f"The {name} price in Kenya ranges from {ksh(lo)} to {ksh(hi)} at {S} ({my}), depending on the "
              f"configuration. We stock {n} {name} variants"
              + (f", {', '.join(conds)}" if conds else "") + ", with M-Pesa payment and delivery countrywide.")
    intro = [
        f"<p>{answer}</p>",
        f"<p>The cheapest option is the <a href=\"/product/{cheapest['slug']}\">{cheapest['name']}</a> at "
        f"{ksh(cheapest['price'])}. "
        + (f"For the best value for money we recommend the <a href=\"/product/{best['slug']}\">{best['name']}</a> at "
           f"{ksh(best['price'])}, which gives the most performance per shilling in this range." if best is not cheapest else
           "It is also the best value in this range.")
        + "</p>",
        "<p>Prices below are updated automatically from our live stock. Every variant comes with a written warranty, "
        "and you can test it at our Nairobi CBD shop before paying.</p>",
    ]
    how = _how_to_pick(name, kind, items)
    faqs = [
        {"q": f"What is the price of the {name} in Kenya?",
         "a": f"At {S}, the {name} costs between {ksh(lo)} and {ksh(hi)} ({my}), depending on processor, RAM and storage."},
        {"q": f"Which {name} variant should I buy?",
         "a": f"For most buyers, the {best['name']} ({ksh(best['price'])}) is the best balance of price and performance. "
              f"On a tight budget, choose the {cheapest['name']} ({ksh(cheapest['price'])})."},
        {"q": f"Is the {name} available for delivery outside Nairobi?",
         "a": "Yes. We deliver to Mombasa, Kisumu, Nakuru, Eldoret, Thika, Nyeri, Machakos and every other town by courier "
              "in 1–3 working days, with same or next-day delivery in Nairobi."},
        {"q": f"Does the {name} come with a warranty?",
         "a": "Yes. " + ("Refurbished units carry a 3-month warranty and new units carry 12 months. " if kind in ("laptop", "desktop")
                         else "Each unit carries the warranty shown on its product page. ")
              + "The warranty is written on your receipt."},
    ]
    return {"slug": slug, "name": name, "kind": kind, "items": [row(x) for x in items], "lo": lo, "hi": hi,
            "updated": my, "answer": answer, "intro_html": "".join(intro), "how_html": how, "faqs": faqs,
            "title": f"{name} Price in Kenya ({my}) – {n} Variants from {ksh(lo)}",
            "meta_description": f"{name} price in Kenya from {ksh(lo)} to {ksh(hi)}. Compare {n} variants side by side, "
                                f"with warranty, M-Pesa payment and countrywide delivery. Updated {my}."[:160]}


def _spec_score(p):
    s = p.get("specs") or {}
    sc = 0
    ram = int(re.sub(r"\D", "", s.get("ram", "0")) or 0)
    sc += min(ram, 32) * 2
    g = re.search(r"(\d{1,2})(?:st|nd|rd|th) Gen", s.get("cpu", "")) or re.search(r"-(\d{4,5})", s.get("cpu", ""))
    if g:
        num = g.group(1)
        sc += (int(num[:2]) if len(num) == 5 else int(num[0]) if len(num) == 4 else int(num)) * 3
    sc += {"i3": 5, "i5": 10, "i7": 15, "i9": 20}.get((re.search(r"i[3579]", s.get("cpu", "")) or [""])[0], 8)
    if "SSD" in s.get("storage", ""):
        sc += 10
    if s.get("gpu"):
        sc += 20
    cap = re.search(r"(\d+)\s*(GB|TB)", p["name"], re.I)
    if p["category"] in ("ram", "storage") and cap:
        sc = int(cap.group(1)) * (1000 if cap.group(2).upper() == "TB" else 1)
    return sc or 1


def _how_to_pick(name, kind, items):
    if kind in ("laptop", "desktop"):
        rams = sorted({x["specs"].get("ram") for x in items if x["specs"].get("ram")})
        cpus = sorted({re.sub(r"\s*\(.*", "", x["specs"].get("cpu", "")) for x in items if x["specs"].get("cpu")})
        tips = []
        if len(cpus) > 1:
            tips.append(f"<li><strong>Processor:</strong> variants come with {', '.join(cpus)}. Core i5 suits students and "
                        "office work; Core i7/i9 suits heavier multitasking and creative software.</li>")
        if len(rams) > 1:
            tips.append(f"<li><strong>RAM:</strong> options include {', '.join(rams)}. Choose 16 GB for programming, "
                        "design and heavy multitasking; 8 GB is fine for Office and browsing.</li>")
        tips.append("<li><strong>Storage:</strong> always prefer an SSD; 512 GB if you keep large files locally.</li>")
        tips.append("<li><strong>Warranty and condition:</strong> check the warranty on each listing and ask for battery "
                    "health on refurbished units.</li>")
        return f"<h2>How to choose the right {name}</h2><ul>{''.join(tips)}</ul>"
    if kind == "ram":
        speeds = sorted({m.group(1) for x in items for m in [re.search(r"(\d{4})\s*MHz|(\d{4})/", x["name"], re.I)] if m and m.group(1)})
        return (f"<h2>Which {name} speed do I need?</h2><p>These modules differ only in speed"
                + (f" ({', '.join(s + ' MHz' for s in speeds)})" if speeds else "")
                + ". Faster DDR4 modules work in slower machines at the machine's speed, so if you're unsure, choose the "
                  "fastest one. For best performance, match the speed of the module already in your computer, or tell us "
                  "your model and we'll confirm.</p>")
    return (f"<h2>Which {name} should I choose?</h2><p>All options here have the same capacity; they differ in form "
            "factor and interface. Check which slot or bay your computer has (M.2 2280, 2242, 2230, mSATA or 2.5-inch), "
            "or send us your model and we'll confirm before you buy.</p>")


# ------------------------------------------------------------------ collections

def _ram(p):
    return int(re.sub(r"\D", "", (p.get("specs") or {}).get("ram", "0")) or 0)


def _gen(p):
    c = (p.get("specs") or {}).get("cpu", "")
    g = re.search(r"\((\d{1,2})(?:st|nd|rd|th) Gen\)", c) or re.search(r"-(\d{4,5})", c)
    if not g:
        return 0
    num = g.group(1)
    return int(num[:2]) if len(num) == 5 else int(num[0]) if len(num) == 4 else int(num)


def _laptop(p):
    return p["category"] in LAPTOP_CATS


COLLECTIONS = [
    # brand
    {"slug": "hp-laptops-price-in-kenya", "group": "Brand", "name": "HP Laptops",
     "h1": "HP Laptops Price in Kenya", "filter": lambda p: _laptop(p) and p["brand"] == "HP",
     "angle": "HP is Kenya's best-selling laptop brand, with the widest range of parts and repair support. Our range covers refurbished EliteBooks and ZBooks, new HP 250 and HP 15 laptops, Spectre convertibles and Omen and Victus gaming laptops."},
    {"slug": "lenovo-laptops-price-in-kenya", "group": "Brand", "name": "Lenovo Laptops",
     "h1": "Lenovo Laptops Price in Kenya", "filter": lambda p: _laptop(p) and p["brand"] == "Lenovo",
     "angle": "Lenovo ThinkPads are famous for their keyboards and durability, IdeaPads for value, ThinkBooks for small business and Legion for gaming."},
    {"slug": "dell-laptops-price-in-kenya", "group": "Brand", "name": "Dell Laptops",
     "h1": "Dell Laptops Price in Kenya", "filter": lambda p: _laptop(p) and p["brand"] == "Dell",
     "angle": "Dell Latitude laptops are built for business, XPS for premium ultraportable use and Alienware for high-end gaming."},
    {"slug": "asus-laptops-price-in-kenya", "group": "Brand", "name": "ASUS Laptops",
     "h1": "ASUS Laptops Price in Kenya", "filter": lambda p: _laptop(p) and p["brand"] == "Asus",
     "angle": "ASUS ExpertBook business laptops are tested to military-grade durability standards, and ROG laptops are built for serious gaming."},
    {"slug": "hp-elitebook-price-in-kenya", "group": "Brand", "name": "HP EliteBook",
     "h1": "HP EliteBook Price in Kenya", "filter": lambda p: _laptop(p) and "elitebook" in p["name"].lower(),
     "angle": "The EliteBook is HP's premium business line: metal chassis, spill-resistant keyboards and strong security, which is why refurbished EliteBooks are Kenya's most popular student and office laptops."},
    {"slug": "lenovo-thinkpad-price-in-kenya", "group": "Brand", "name": "Lenovo ThinkPad",
     "h1": "Lenovo ThinkPad Price in Kenya", "filter": lambda p: _laptop(p) and ("thinkpad" in p["name"].lower() or "x1 carbon" in p["name"].lower()),
     "angle": "ThinkPads are known for the best keyboards on any laptop, the red TrackPoint and legendary durability, and are easy to repair in Nairobi."},
    {"slug": "hp-zbook-price-in-kenya", "group": "Brand", "name": "HP ZBook",
     "h1": "HP ZBook Mobile Workstations Price in Kenya", "filter": lambda p: "zbook" in p["name"].lower(),
     "angle": "ZBooks are HP's mobile workstations with dedicated NVIDIA graphics, built for AutoCAD, Revit, ArcGIS, SolidWorks and video editing."},
    # budget
    {"slug": "laptops-under-20000-in-kenya", "group": "Budget", "name": "Laptops under KES 20,000",
     "h1": "Best Laptops Under KES 20,000 in Kenya", "filter": lambda p: _laptop(p) and p["price"] <= 20000,
     "angle": "Under 20,000 shillings, refurbished business laptops give you the most reliable machine for typing, browsing, online classes and eCitizen/KRA forms."},
    {"slug": "laptops-under-30000-in-kenya", "group": "Budget", "name": "Laptops under KES 30,000",
     "h1": "Best Laptops Under KES 30,000 in Kenya", "filter": lambda p: _laptop(p) and p["price"] <= 30000,
     "angle": "The KES 20,000–30,000 range is the sweet spot for refurbished Core i5 business laptops with SSDs, ideal for university students and office work."},
    {"slug": "laptops-under-50000-in-kenya", "group": "Budget", "name": "Laptops under KES 50,000",
     "h1": "Best Laptops Under KES 50,000 in Kenya", "filter": lambda p: _laptop(p) and p["price"] <= 50000,
     "angle": "Up to KES 50,000 you can get 8th–11th Gen Core i5/i7 laptops with 16 GB RAM, touchscreens and convertibles, which are great for professionals and programmers."},
    {"slug": "laptops-under-100000-in-kenya", "group": "Budget", "name": "Laptops under KES 100,000",
     "h1": "Best Laptops Under KES 100,000 in Kenya", "filter": lambda p: _laptop(p) and 50000 < p["price"] <= 100000,
     "angle": "Between KES 50,000 and 100,000 you can choose brand-new laptops with full manufacturer warranty or powerful refurbished mobile workstations."},
    # use
    {"slug": "best-laptops-for-students-in-kenya", "group": "Use", "name": "Laptops for students",
     "h1": "Best Laptops for University Students in Kenya", "filter": lambda p: _laptop(p) and p["price"] <= 60000 and _ram(p) >= 8 and _gen(p) >= 6,
     "angle": "We picked laptops with at least 8 GB RAM, an SSD and a 6th Gen or newer processor, priced for students: fast enough for assignments, research, Zoom classes and programming coursework."},
    {"slug": "best-laptops-for-programming-in-kenya", "group": "Use", "name": "Laptops for programming",
     "h1": "Best Laptops for Programming and Software Development in Kenya", "filter": lambda p: _laptop(p) and _ram(p) >= 16,
     "angle": "Developers need RAM above all: every laptop here has 16 GB or more for IDEs, Docker, emulators and dozens of browser tabs."},
    {"slug": "laptops-for-autocad-engineering-in-kenya", "group": "Use", "name": "Laptops for AutoCAD & engineering",
     "h1": "Best Laptops for AutoCAD, Revit and Engineering in Kenya", "filter": lambda p: _laptop(p) and bool((p.get("specs") or {}).get("gpu")),
     "angle": "Every laptop here has dedicated NVIDIA graphics, which accelerates AutoCAD 3D, Revit, SketchUp, ArcGIS, SolidWorks and video rendering."},
    {"slug": "gaming-laptops-price-in-kenya", "group": "Use", "name": "Gaming laptops",
     "h1": "Gaming Laptops Price in Kenya", "filter": lambda p: p["category"] == "gaming-laptops",
     "angle": "HP Omen, Alienware, Lenovo Legion, ASUS ROG and HP Victus with NVIDIA RTX graphics, both new and tested slightly-used units."},
    {"slug": "touchscreen-2-in-1-laptops-in-kenya", "group": "Use", "name": "Touchscreen & 2-in-1 laptops",
     "h1": "Touchscreen and 2-in-1 Laptops in Kenya", "filter": lambda p: _laptop(p) and ((p.get("specs") or {}).get("touchscreen") or (p.get("specs") or {}).get("form_factor")),
     "angle": "Convertible laptops fold into tablet mode for note-taking, presenting and drawing, which is popular with students, lecturers and managers."},
    {"slug": "business-laptops-in-kenya", "group": "Use", "name": "Business laptops",
     "h1": "Best Business Laptops in Kenya", "filter": lambda p: _laptop(p) and re.search(r"elitebook|latitude|thinkpad|x1 carbon|expertbook|thinkbook|probook", p["name"], re.I),
     "angle": "Business-grade lines (EliteBook, Latitude, ThinkPad, ExpertBook, ThinkBook, ProBook) are built tougher, have better keyboards and security features, and are easier to repair."},
    {"slug": "lightweight-laptops-in-kenya", "group": "Use", "name": "Lightweight laptops",
     "h1": "Lightweight and Compact Laptops in Kenya (12–13.5\")", "filter": lambda p: _laptop(p) and (p.get("specs") or {}).get("display") and float((p.get("specs") or {}).get("display", "0").rstrip('"')) <= 13.5,
     "angle": "Compact 12.5–13.5-inch laptops are the easiest to carry around campus, on matatus and between meetings."},
    # other categories
    {"slug": "ink-tank-printers-price-in-kenya", "group": "Printers", "name": "Ink tank printers",
     "h1": "Ink Tank Printers Price in Kenya", "filter": lambda p: p["category"] == "printers" and re.search(r"ecotank|pixma g|smart tank|l8100", p["name"], re.I),
     "angle": "Ink tank printers (Epson EcoTank, Canon PIXMA G, HP Smart Tank) have the lowest cost per page for regular colour printing at home, school and in cyber cafés."},
    {"slug": "laser-printers-price-in-kenya", "group": "Printers", "name": "Laser printers",
     "h1": "Laser Printers Price in Kenya", "filter": lambda p: p["category"] == "printers" and re.search(r"laser|i-sensys", p["name"], re.I),
     "angle": "Laser printers are the fastest and most reliable choice for black-and-white office documents."},
    {"slug": "ssd-price-in-kenya", "group": "Upgrades", "name": "SSDs",
     "h1": "SSD Price in Kenya: SATA, M.2 NVMe and mSATA", "filter": lambda p: p["category"] == "storage" and "ssd" in p["name"].lower(),
     "angle": "Upgrading to an SSD is the fastest way to make a slow computer feel new. We fit and clone your drive for free in-store."},
    {"slug": "laptop-ram-price-in-kenya", "group": "Upgrades", "name": "Laptop RAM",
     "h1": "Laptop RAM Price in Kenya (DDR3 & DDR4)", "filter": lambda p: p["category"] == "ram" and "laptop" in p["name"].lower(),
     "angle": "Add more RAM to make Windows, Chrome and Office run smoothly. We fit laptop RAM for free when you buy from us."},
    {"slug": "refurbished-desktops-price-in-kenya", "group": "Desktops", "name": "Refurbished desktops",
     "h1": "Refurbished Desktop Computers Price in Kenya", "filter": lambda p: p["category"] == "desktops" and p["condition"] == "refurbished",
     "angle": "Refurbished Dell OptiPlex, HP ProDesk/EliteDesk and Lenovo ThinkCentre desktops are the reliable, low-cost choice for offices, schools and cyber cafés."},
]


def collection_index():
    out = []
    for c in COLLECTIONS:
        items = [p for p in products() if c["filter"](p)]
        if len(items) >= 3:
            out.append({"slug": c["slug"], "name": c["name"], "group": c["group"], "count": len(items),
                        "min": min(x["price"] for x in items)})
    return out


def collection_page(slug):
    c = next((x for x in COLLECTIONS if x["slug"] == slug), None)
    if not c:
        return None
    items = sorted((p for p in products() if c["filter"](p)), key=lambda x: x["price"])
    if len(items) < 3:
        return None
    S, my, n = site(), month_year(), len(items)
    lo, hi = items[0]["price"], items[-1]["price"]
    picks = _top_picks(items)
    answer = (f"{c['h1'].replace(' in Kenya', '')} in Kenya start from {ksh(lo)}"
              f" and go up to {ksh(hi)} at {S} ({my}). We currently stock {n} options"
              + (f"; our top pick is the {picks[0][1]['name']} at {ksh(picks[0][1]['price'])}" if picks else "") + ".")
    picks_html = "".join(
        f"<li><strong>{label}:</strong> <a href=\"/product/{p['slug']}\">{p['name']}</a> – {ksh(p['price'])}</li>"
        for label, p in picks)
    intro = (f"<p>{answer}</p><p>{c['angle']}</p>"
             + (f"<h2>Our top picks ({my})</h2><ul>{picks_html}</ul>" if picks_html else ""))
    brands = sorted({p["brand"] for p in items})
    faqs = [
        {"q": f"How much are {c['name'].lower()} in Kenya?",
         "a": f"At {S}, prices range from {ksh(lo)} to {ksh(hi)} ({my}), across {n} models."},
        {"q": f"What is the cheapest option?",
         "a": f"The {items[0]['name']} at {ksh(items[0]['price'])}."},
        {"q": "Can I pay with M-Pesa and get delivery outside Nairobi?",
         "a": "Yes. Pay by M-Pesa STK push at checkout, then choose free pickup in Nairobi CBD, same/next-day Nairobi delivery, "
              "or courier delivery to Mombasa, Kisumu, Nakuru, Eldoret and all other towns in 1–3 days."},
    ]
    if len(brands) > 1:
        faqs.append({"q": "Which brands are available?", "a": f"{', '.join(brands)}."})
    return {"slug": slug, "name": c["name"], "group": c["group"], "h1": c["h1"], "updated": my, "answer": answer,
            "intro_html": intro, "items": [row(x) for x in items], "lo": lo, "hi": hi, "faqs": faqs,
            "title": f"{c['h1']} ({my}) – From {ksh(lo)}",
            "meta_description": f"{c['h1']}: {n} options from {ksh(lo)} to {ksh(hi)}. Compare prices and specs, pay with "
                                f"M-Pesa, warranty included, delivery countrywide. Updated {my}."[:160],
            "related": [x for x in collection_index() if x["slug"] != slug and x["group"] == c["group"]][:6]}


def _top_picks(items):
    if len(items) < 3:
        return []
    by_value = max(items, key=lambda x: _spec_score(x) / max(x["price"], 1))
    cheapest = items[0]
    best = max(items, key=lambda x: (_spec_score(x), -x["price"]))
    picks, seen = [], set()
    for label, p in (("Best value", by_value), ("Cheapest", cheapest), ("Most powerful", best)):
        if p["slug"] not in seen:
            picks.append((label, p))
            seen.add(p["slug"])
    return picks


# ------------------------------------------------------------------ price list

def laptop_price_list():
    my = month_year()
    groups = defaultdict(list)
    for p in products():
        if p["category"] in LAPTOP_CATS:
            groups[p["brand"] if p["brand"] != "Generic" else "Other"].append(row(p))
    for v in groups.values():
        v.sort(key=lambda x: x["price"])
    all_items = [x for v in groups.values() for x in v]
    lo = min(x["price"] for x in all_items)
    hi = max(x["price"] for x in all_items)
    bands = [("Under KES 20,000", 0, 20000), ("KES 20,000–30,000", 20001, 30000), ("KES 30,000–50,000", 30001, 50000),
             ("KES 50,000–100,000", 50001, 100000), ("Over KES 100,000", 100001, 10**9)]
    band_rows = [(label, sum(1 for x in all_items if a <= x["price"] <= b)) for label, a, b in bands]
    return {"updated": my, "groups": [{"brand": k, "items": v} for k, v in sorted(groups.items(), key=lambda kv: -len(kv[1]))],
            "count": len(all_items), "lo": lo, "hi": hi, "bands": band_rows,
            "answer": (f"Laptop prices in Kenya at {site()} range from {ksh(lo)} for a refurbished entry-level model to "
                       f"{ksh(hi)} for a high-end gaming laptop ({my})."
                       + _typical("a refurbished Core i5 laptop", [x for x in all_items if x["condition"] == "refurbished"
                                                                  and "i5" in x["cpu"] and x["category"] != "gaming-laptops"])
                       + _typical("a new laptop", [x for x in all_items if x["category"] == "new-laptops"]))}


def _typical(label, items):
    """Middle 80% price range, so the summary sentence always matches live prices."""
    prices = sorted(x["price"] for x in items)
    if len(prices) < 3:
        return ""
    a, b = prices[len(prices) // 10], prices[min(len(prices) - 1, (len(prices) * 9) // 10)]
    return f" Most {label.split(' ', 1)[1]}s cost between {ksh(a)} and {ksh(b)}."
