"""Builds the product catalogue from data/catalogue_source.txt.

- Prices: 10% below the captured price (PRICE_FACTOR), rounded to the nearest shilling.
- Only facts are reused (product names, specs, prices). Descriptions, SEO text and FAQs are written
  here from the specs; no copy or images are taken from the source site.
- Every product gets a category, brand, condition, specs parsed from its name, a warranty and
  a default stock of DEFAULT_STOCK: set real stock in the admin before going live.
"""
import re
from pathlib import Path

from .utils import slugify

SOURCE = Path(__file__).parent / "data" / "catalogue_source.txt"
PRICE_FACTOR = 0.90
DEFAULT_STOCK = 5

BRANDS = ["HP", "Dell", "Lenovo", "Asus", "Alienware", "Apple", "Canon", "Epson", "Logitech", "Anker", "Bose",
          "Honeywell", "ZKTeco", "SecuGen", "Xprinter", "Xiaomi", "Mercury", "Cursor", "Marken", "Power King",
          "DYMO", "Evolis", "Garrett", "SwissGear", "Kalobee", "KINGZONE", "SMART KING", "Syble", "PAVAREAL",
          "North Bayou", "Starlink", "Epos", "Sensormatic"]

NEW_LAPTOP_HINTS = ["hp 15", "hp 250", "250g", "15s-", "ideapad", "thinkbook", "expertbook", "spectre", "omnibook",
                    "probook 440 g10", "pavilion", "v14 g5", "thinkpad e14", "t14 gen", "xps 13 9315", "x543u",
                    "rog ", "840 g9", "victus"]

# (category, test) — first match wins. Order matters.
RULES = [
    ("gaming-laptops", lambda n: any(k in n for k in ["alienware", "omen", "legion", "rog ", "victus"])),
    ("pos-supplies", lambda n: any(k in n for k in ["label", "thermal roll", "paper roll", "ribbon", "ink cartridge",
                                                     "carbonless", "magnetic stripe cards", "packing tape",
                                                     "double-sided tape", "warning tape"])
     and not any(k in n for k in ["labeler", "label maker", "label printer", "deactivator", "eas "])
     and ("printer" not in n or any(k in n for k in ["paper", "roll", "ribbon", "labels", "cartridge"]))),
    ("security-equipment", lambda n: any(k in n for k in ["eas ", "eas,", "security tag", "hard tag", "tags", "detacher",
                                                           "em strips", "anti-shoplifting", "antitheft system",
                                                           "em label", "boom barrier", "under vehicle",
                                                           "garrett", "safe box"])),
    ("cctv", lambda n: "cctv" in n or ("camera" in n and "security" in n)),
    ("biometric-time-attendance", lambda n: any(k in n for k in ["fingerprint", "biometric", "time attendance",
                                                                  "maglock", "push to exit", "door closure",
                                                                  "hotel room smart lock", "hotel card",
                                                                  "energy saving switch"])),
    ("pos-systems", lambda n: any(k in n for k in ["pos ", "pos terminal", "pos)", "barcode scanner", "barcode printer",
                                                    "barcode transfer printer", "receipt printer", "cash drawer",
                                                    "vfd", "msr", "magnetic swipe", "etims", "xprinter",
                                                    "thermal printer adapter", "handheld barcode", "inventry pos",
                                                    "scanners-mountable", "scanners mountable"])),
    ("business-equipment", lambda n: any(k in n for k in ["money count", "bill counter", "laminating", "queue",
                                                           "qms", "calling pad", "ticket machine", "label maker",
                                                           "labeler", "label printer", "price tagging", "card printer",
                                                           "expiry date", "tally counter", "projector",
                                                           "crimping"])),
    ("ups-power", lambda n: any(k in n for k in ["ups", "extension", "power cable"])),
    ("printers", lambda n: any(k in n for k in ["printer", "ecotank", "pixma", "laserjet", "i-sensys", "smart tank",
                                                 "deskjet", "dot matrix"])),
    ("monitors", lambda n: any(k in n for k in ["monitor", "edge to edge"]) and not any(k in n for k in ["stand", "bracket"])),
    ("ram", lambda n: re.search(r"\b(ddr\d|ram)\b", n) and not re.search(r"core|xeon|celeron|cerelon|laptop$", n)
     and "gb" in n and not any(k in n for k in ["ssd", "hdd", "hard disk", "tv box"]) or "gaming ram" in n),
    ("storage", lambda n: any(k in n for k in ["ssd", "hard disk", "nvme", "msata", "m.2", "m2 "])
     and not re.search(r"core|xeon|celeron|cerelon|ryzen|i[3579][ -]|\bi[3579]\b", n)),
    ("desktops", lambda n: any(k in n for k in ["optiplex", "prodesk", "elitedesk", "thinkcentre", "workstation",
                                                 "proliant", "server", "all in one", "desktop", "cpu only",
                                                 "microtower", "z240", "mini pc", "z2 g4", "precision"])),
    ("audio-gadgets", lambda n: any(k in n for k in ["speaker", "earbuds", "earphone", "headphone", "tablet", "tv stick",
                                                      "tv box", "controller", "dualshock", "vlogging", "lavalier",
                                                      "fan with"])),
    ("cables-networking", lambda n: any(k in n for k in ["cable", "adapter", "converter", "convertor", "hdmi", "vga",
                                                          "rj45", "poe", "wifi adapter", "ethernet", "displayport",
                                                          "usb to lan", "enclosure", "pcie"])),
    ("laptops", lambda n: any(k in n for k in ["elitebook", "latitude", "thinkpad", "zbook", "xps", "yoga", "x1 carbon",
                                                "elite x2", "ideapad", "thinkbook", "expertbook", "spectre", "omnibook",
                                                "probook", "pavilion", "laptop", "notebook", "lenovo v14", "x543u",
                                                "hp 15", "hp 250", "15s-"]) and "keyboard" not in n and "bag" not in n
                                                and "charger" not in n and "stand" not in n and "backpack" not in n),
    ("accessories", lambda n: True),
]


def _num(s):
    s = s.strip().replace(",", "")
    return None if s in ("", "-") else float(s)


def parse_source():
    rows = []
    for line in SOURCE.read_text(encoding="utf-8").splitlines():
        if not line.strip() or line.startswith("#"):
            continue
        name, price, orig = [p.strip() for p in line.rsplit("|", 2)]
        rows.append((name, _num(price), _num(orig)))
    return rows


TOKEN_CASE = {
    "hp": "HP", "elitebook": "EliteBook", "probook": "ProBook", "zbook": "ZBook", "thinkpad": "ThinkPad", "ideapad": "IdeaPad",
    "thinkbook": "ThinkBook", "expertbook": "ExpertBook", "optiplex": "OptiPlex", "prodesk": "ProDesk", "elitedesk": "EliteDesk",
    "thinkcentre": "ThinkCentre", "ssd": "SSD", "hdd": "HDD", "ram": "RAM", "gb": "GB", "tb": "TB", "nvme": "NVMe",
    "msata": "mSATA", "dos": "DOS", "wins": "Windows", "win": "Windows", "nvidia": "NVIDIA", "rtx": "RTX", "intel": "Intel",
    "ups": "UPS", "usb": "USB", "hdmi": "HDMI", "vga": "VGA", "lan": "LAN", "pos": "POS", "eas": "EAS", "em": "EM",
    "led": "LED", "rgb": "RGB", "ddr3": "DDR3", "ddr4": "DDR4", "ddr5": "DDR5", "mhz": "MHz", "x360": "x360",
    "dell": "Dell", "lenovo": "Lenovo", "asus": "ASUS", "rog": "ROG", "xps": "XPS", "tv": "TV", "wifi": "WiFi",
    "etims": "eTIMS", "qms": "QMS", "vfd": "VFD", "msr": "MSR", "poe": "PoE", "sata": "SATA", "pcie": "PCIe",
    "fhd": "FHD", "i-sensys": "i-SENSYS", "khz": "kHz", "mfp": "MFP", "uhd": "UHD", "4k": "4K", "omen": "Omen", "victus": "Victus", "legion": "Legion", "spectre": "Spectre",
}
SMALL_WORDS = {"with", "and", "for", "of", "in", "to", "the", "a", "or", "by", "on", "per", "x"}


def fix_case(name):
    def word(w):
        core = re.match(r"^([\W]*)(.*?)([\W]*)$", w)
        pre, mid, post = core.groups()
        low = mid.lower()
        if low in TOKEN_CASE:
            mid = TOKEN_CASE[low]
        elif re.fullmatch(r"\d+(gb|tb|mhz|va|w|mah|mm)", low):
            num, unit = re.match(r"(\d+)(\D+)", low).groups()
            mid = num + {"gb": "GB", "tb": "TB", "mhz": "MHz", "va": "VA", "w": "W", "mah": "mAh", "mm": "mm"}[unit]
        elif re.fullmatch(r"\d+(ssd|hdd)", low):
            num, unit = re.match(r"(\d+)(\D+)", low).groups()
            mid = f"{num}GB {unit.upper()}"
        elif re.fullmatch(r"\d{4,5}[uhgk]\d?", low):
            mid = mid.upper()
        elif low == "x1":
            mid = "X1"
        elif re.fullmatch(r"g\d{1,2}", low):
            mid = mid.upper()
        elif re.fullmatch(r"\d{1,2}(st|nd|rd|th)", low):
            mid = low
        elif low == "gen":
            mid = "Gen"
        elif low == "core":
            mid = "Core"
        elif mid and mid[0].islower() and not re.search(r"\d", mid) and low not in SMALL_WORDS:
            mid = mid[0].upper() + mid[1:]
        return pre + mid + post
    parts = re.split(r"([ ,/])", name)
    out = [word(w) if w not in (" ", ",", "/") else w for w in parts]
    out = [w for w in out if w != ""]
    if out and out[0][:1].islower() and not re.match(r"i\d", out[0]):
        out[0] = out[0][0].upper() + out[0][1:]
    return "".join(out)


def clean_name(name):
    name = re.sub(r"\s*\(Copy\)\s*", " ", name)
    name = name.replace("|", "–").replace("Cerelon", "Celeron").replace("Inventry", "Inventory")
    name = re.sub(r"\s+in Kenya\b", "", name)
    name = re.sub(r"\s*:.*$", "", name)
    name = re.sub(r"\s+", " ", name).strip(" ,–-")
    return fix_case(name)


def brand_of(name):
    low = name.lower()
    for b in BRANDS:
        if re.search(r"(^|[^a-z])" + re.escape(b.lower()) + r"([^a-z]|$)", low):
            return {"Alienware": "Dell"}.get(b, b)
    return "Generic"


def category_of(name):
    n = " " + name.lower() + " "
    for cat, test in RULES:
        if test(n):
            if cat == "laptops":
                return "new-laptops" if any(h in n for h in NEW_LAPTOP_HINTS) else "refurbished-laptops"
            return cat
    return "accessories"


def condition_of(name, cat):
    n = name.lower()
    if "slightly used" in n or "(refurbished" in n or n.startswith("refurbished") or "– refurbished" in n \
            or n.endswith(" refurbished") or cat == "refurbished-laptops":
        return "refurbished"
    if cat == "gaming-laptops":
        return "refurbished" if "slightly used" in n else "new"
    if cat == "desktops" and any(k in n for k in ["optiplex", "prodesk", "elitedesk", "thinkcentre", "z440", "z820",
                                                  "precision", "proliant", "z2 g4", "z240", "cpu only", "290 g4"]):
        return "refurbished"
    if cat == "monitors" and any(k in n for k in ["le1901", "1909w", "l19 ", "17 inch", "edge to edge"]):
        return "refurbished"
    return "new"


def specs_of(name):
    s = {}
    n = name.replace("\u2011", "-")
    # --- CPU ---
    m = re.search(r"Core\s*Ultra\s*(\d)\s*(\d{3}[A-Z]?)?", n, re.I)
    if m:
        s["cpu"] = f"Intel Core Ultra {m.group(1)}" + (f" {m.group(2)}" if m.group(2) else "")
    else:
        m = (re.search(r"Core[\s-]*i?([3579])(?:\s*\(|[\s-]*)(\d{4,5}[A-Z]{0,2}\d?)?", n, re.I)
             or re.search(r"\bC?i([3579])(?:[\s-]*(\d{4,5}[A-Z]{0,2}))?\b", n, re.I))
        if m:
            cpu = f"Intel Core i{m.group(1)}" + (f"-{m.group(2).upper()}" if m.group(2) else "")
            gen = re.search(r"(\d{1,2})(?:th|rd|nd|st)\b", n, re.I)
            if gen:
                cpu += f" ({gen.group(1)}th Gen)".replace("2th", "2nd").replace("3th", "3rd").replace("1th", "1st") \
                    if gen.group(1) in ("1", "2", "3") else f" ({gen.group(1)}th Gen)"
            s["cpu"] = cpu
        else:
            m = re.search(r"Xeon(?:\s+(E\d-\d{4}\w*(?:\s*v\d)?))?", n, re.I) or re.search(r"Cele?ron", n, re.I)
            if m:
                s["cpu"] = "Intel " + (f"Xeon {m.group(1)}" if m.lastindex and m.group(1) else
                                       ("Xeon" if "xeon" in m.group(0).lower() else "Celeron"))
    # --- GPU (find first so its GB isn't mistaken for RAM) ---
    gpu_spans = []
    m = re.search(r"RTX\s*(\d{4})", n, re.I)
    if m:
        vram = (re.search(r"RTX\s*\d{4}\s*(?:with\s*)?()(\d{1,2})\s*GB", n, re.I)
                or re.search(r"\b(\d{1,2})\s*GB\s*(?:Nvidia\s*)?RTX", n, re.I))
        v = vram and next((g for g in vram.groups() if g), None)
        s["gpu"] = f"NVIDIA GeForce RTX {m.group(1)}" + (f" {v}GB" if v else "")
        if vram:
            gpu_spans.append(vram.span())
    else:
        m = re.search(r"(\d+)\s*GB\s*(?:Nvidia|NVidia)(?:\s*GPU)?|(\d+)\s*GB\s*Nvidia", n, re.I)
        if m:
            s["gpu"] = f"NVIDIA {m.group(1) or m.group(2)}GB dedicated graphics"
            gpu_spans.append(m.span())
    def in_gpu(pos):
        return any(a <= pos < b for a, b in gpu_spans)
    # --- storage ---
    st = re.search(r"(\d+(?:\.\d)?)\s*(GB|TB)?\s*(SSD|HDD|Hard\s*Disk)", n, re.I)
    st_span = None
    if st:
        size = st.group(1) + (st.group(2) or "GB").upper()
        kind = "SSD" if st.group(3).upper() == "SSD" else "HDD"
        s["storage"] = f"{size} {kind}"
        st_span = st.span()
    # --- RAM: first sensible GB value not used by storage or GPU ---
    for m in re.finditer(r"(\d{1,2})\s*GB", n, re.I):
        if in_gpu(m.start()) or (st_span and st_span[0] <= m.start() < st_span[1]):
            continue
        if int(m.group(1)) in (2, 4, 8, 12, 16, 32, 64):
            s["ram"] = f"{m.group(1)}GB"
            break
    if "storage" not in s and "ram" in s:
        for m in re.finditer(r"(\d{3,4})\s*GB|(\d)\s*TB", n, re.I):
            if not in_gpu(m.start()):
                s["storage"] = (f"{m.group(1)}GB" if m.group(1) else f"{m.group(2)}TB")
                break
    # --- display, touch, OS ---
    d = re.search(r"(\d{2}(?:\.\d)?)\s*(?:\u2033|\u201d|\"|-?\s*inch(?:es)?)", n, re.I)
    if d and 10 <= float(d.group(1)) <= 34:
        s["display"] = f'{d.group(1)}"'
    if re.search(r"touch", n, re.I):
        s["touchscreen"] = "Yes"
    if re.search(r"x360|flip|yoga|convertible|detachable", n, re.I):
        s["form_factor"] = "2-in-1 convertible"
    if re.search(r"\bdos\b|no os", n, re.I):
        s["os"] = "No Windows (FreeDOS)"
    elif re.search(r"win(dows|s)?\s*11", n, re.I):
        s["os"] = "Windows 11"
    return s


# Shown on the homepage "Best sellers" row: a spread of popular laptops, desktops and POS
FEATURED = ["elitebook 840 g5 core i5", "ThinkPad T480s", "X1 Carbon Intel core i7-8565U", "ZBook Power 15 i7 11th",
            "x360 1040 G8 Core i7 11th Gen,16GB", "Omen i9 13th gen 16GB ram 1TB SSD RTX 4060", "OptiPlex 3070",
            "15\u2033 All-in-One Pos Touch Terminal Core i5"]

WARRANTY = {"refurbished": 3, "new": 12}
NO_WARRANTY_CATS = {"pos-supplies"}

CAT_BLURB = {
    "refurbished-laptops": "a tested, refurbished business laptop",
    "new-laptops": "a brand-new laptop",
    "gaming-laptops": "a high-performance gaming laptop",
    "desktops": "a desktop computer",
    "monitors": "a computer monitor",
    "printers": "a printer",
    "storage": "a storage drive",
    "ram": "a memory (RAM) module",
    "pos-systems": "point-of-sale (POS) equipment",
    "pos-supplies": "a POS and labelling consumable",
    "cctv": "a security camera product",
    "security-equipment": "retail security and anti-theft equipment",
    "biometric-time-attendance": "a biometric, access control or hotel locking device",
    "ups-power": "a power backup or power distribution product",
    "business-equipment": "business and office equipment",
    "audio-gadgets": "an audio or gadget product",
    "cables-networking": "a cable, adapter or networking accessory",
    "accessories": "a computer accessory",
}

USE_CASE = {
    "refurbished-laptops": "students, office work and business users who want reliable performance for less",
    "new-laptops": "anyone who wants a new machine with full manufacturer warranty",
    "gaming-laptops": "gaming, 3D, video editing and engineering software",
    "desktops": "offices, cyber cafés, schools and home use",
    "monitors": "office, home and dual-screen setups",
    "printers": "homes, offices and businesses",
    "storage": "upgrading or replacing the drive in a laptop, desktop or CCTV recorder",
    "ram": "upgrading a laptop or desktop for smoother multitasking",
    "pos-systems": "shops, supermarkets, restaurants and pharmacies",
    "pos-supplies": "shops, warehouses and businesses that print receipts and labels",
    "security-equipment": "supermarkets, clothing stores, libraries and premises security",
    "biometric-time-attendance": "offices, factories, schools and hotels",
    "ups-power": "protecting computers and electronics from power cuts and surges",
    "business-equipment": "banks, shops, hospitals, offices and service counters",
    "audio-gadgets": "entertainment, content creation and everyday use",
    "cables-networking": "connecting computers, screens and networks",
    "accessories": "everyday computer and laptop use",
}


SPEC_LABEL = {"cpu": "Processor", "ram": "RAM", "storage": "Storage", "gpu": "Graphics", "display": "Screen size",
              "touchscreen": "Touchscreen", "form_factor": "Form factor", "os": "Operating system"}


def ordered_specs(specs):
    return {k: specs[k] for k in SPEC_LABEL if k in specs}


def description(name, cat, cond, specs, warranty):
    rows = "".join(f"<li><strong>{SPEC_LABEL.get(k, k)}:</strong> {v}</li>" for k, v in specs.items())
    cond_txt = {
        "refurbished": "Professionally refurbished: tested on our checklist, cleaned and repaired where needed. "
                       "Light cosmetic marks are possible.",
        "new": "Brand new.",
        "ex-uk": "Ex-UK, tested and cleaned before sale.",
    }[cond]
    parts = [f"<p>The {name} is {CAT_BLURB.get(cat, 'a product')} suited to {USE_CASE.get(cat, 'everyday use')}.</p>"]
    if rows:
        parts.append(f"<h2>Key specifications</h2><ul>{rows}</ul>")
    parts.append(f"<h2>Condition</h2><p>{cond_txt}</p>")
    if warranty:
        parts.append(f"<h2>Warranty</h2><p>{warranty}-month warranty against hardware faults. "
                     f"Bring it to our Nairobi CBD shop or call us for support.</p>")
    parts.append("<h2>Delivery and payment</h2><p>Pay with M-Pesa at checkout. Free pickup in Nairobi CBD, "
                 "same/next-day delivery in Nairobi and 1–3 days countrywide.</p>")
    return "".join(parts)


def short_of(name, cat, specs):
    bits = [specs.get(k) for k in ("cpu", "ram", "storage") if specs.get(k)]
    use = USE_CASE.get(cat, "everyday use")
    return (f"{' · '.join(bits)}. " if bits else "") + f"Ideal for {use}."


def meta_desc(cond_word, name, price, warranty, site):
    parts = [f"{cond_word} {name} at KES {price:,}" + (f" with {warranty}-month warranty." if warranty else "."),
             "Pay via M-Pesa, pick up in Nairobi or get it delivered.", f"{site}."]
    out = ""
    for p in parts:
        if len((out + " " + p).strip()) <= 160:
            out = (out + " " + p).strip()
    if not out:
        out = parts[0][:157].rsplit(" ", 1)[0] + "…"
    return out


def build_products(site_name, with_content=True):
    products, seen = [], set()
    featured_slugs = 0
    for raw_name, price, orig in parse_source():
        name = clean_name(raw_name)
        slug = slugify(name)
        base, i = slug, 2
        while slug in seen:  # same name twice in the source (e.g. a duplicated listing)
            slug = f"{base}-{i}"
            i += 1
        if base in seen:
            continue  # skip exact duplicate listings rather than publishing two identical pages
        seen.add(slug)

        cat = category_of(name)
        cond = condition_of(name, cat)
        specs = ordered_specs(specs_of(name)) if cat in ("refurbished-laptops", "new-laptops", "gaming-laptops", "desktops") else {}
        new_price = max(1, round(price * PRICE_FACTOR))
        compare = round(orig * PRICE_FACTOR) if orig and orig > price else 0
        warranty = 0 if cat in NO_WARRANTY_CATS or new_price < 300 else WARRANTY[cond]
        cond_word = {"new": "New", "refurbished": "Refurbished", "ex-uk": "Ex-UK"}[cond]
        featured = any(f.lower() in name.lower() for f in FEATURED)
        products.append({
            "name": name, "slug": slug, "brand": brand_of(name), "category": cat, "condition": cond,
            "price": new_price, "compare_at": compare, "stock": DEFAULT_STOCK, "warranty_months": warranty,
            "featured": featured, "specs": specs, "short": short_of(name, cat, specs),
            "description": description(name, cat, cond, specs, warranty),
            "meta_title": f"{name} Price in Kenya",
            "meta_description": meta_desc(cond_word, name, new_price, warranty, site_name),
            "faqs": [
                {"q": f"What is the price of the {name} in Kenya?",
                 "a": f"The {name} costs KES {new_price:,} at {site_name}"
                      + (f", with a {warranty}-month warranty." if warranty else ".")},
                {"q": "How fast is delivery?",
                 "a": "Orders paid before 3pm are delivered the same day within Nairobi. Countrywide courier takes "
                      "1–3 working days. You can also pick up from our shop in Nairobi CBD."},
            ],
            "images": [], "active": True, "source_price": price,
        })
    if with_content:
        from .content.engine import apply
        from .seed_categories import CATEGORIES
        apply(products, CATEGORIES, site_name)
    return products
