"""Variant-specific sections so near-identical products (sizes, speeds, form factors) get genuinely different content."""
import re

from .common import h2, p, ul, table, money

# ---------------- RAM ----------------
RAM_CAP = {
    4: ("4 GB is an entry-level amount today. It suits a single-task machine (a POS till, a reception PC or a "
        "child's homework laptop), or a second stick added to an existing 4 GB to reach 8 GB in dual channel. On its "
        "own it will feel slow with Windows 10/11 plus a modern browser.",
        ["Older laptops and desktops that only need a top-up", "POS tills and kiosk PCs", "Pairing with an existing 4 GB stick"]),
    8: ("8 GB is the most popular upgrade size. Adding an 8 GB stick to a 4 GB machine (12 GB total) or replacing a "
        "4 GB stick gives Windows enough room for Office, a browser with many tabs and a video call at the same time. "
        "Two 8 GB sticks (16 GB) in dual channel is the sweet spot for most professionals.",
        ["Office and school laptops", "Remote workers on Zoom/Teams", "Building 16 GB in dual channel"]),
    16: ("16 GB is the modern standard for heavy multitasking. It keeps Photoshop, Chrome with dozens of tabs, "
         "Teams, Excel models and development tools open without slowdowns, and is the recommended minimum for "
         "gaming and engineering software today. One 16 GB stick also leaves a slot free for future expansion.",
         ["Programmers, designers and analysts", "Gamers and engineering students", "Workstations and mobile workstations"]),
    32: ("32 GB is for demanding professional work: 4K video editing, large Revit/AutoCAD models, GIS, virtual "
         "machines, Docker containers and big datasets. In a two-slot laptop, two 32 GB sticks give 64 GB on "
         "supported machines, which is enough for nearly any workload.",
         ["Video editors and 3D artists", "Developers running virtual machines", "Data analysts and engineers"]),
}
RAM_SPEED = {
    "1333": "1333 MHz (PC3-10600) is the original DDR3 speed used by 2nd-generation Intel Core (Sandy Bridge) machines and many older AMD systems. It also works in most 3rd-gen systems, which run it at 1333 MHz.",
    "1600": "1600 MHz (PC3-12800) is the common DDR3 speed for 3rd- and 4th-generation Intel Core machines. It is backward-compatible with 1333 MHz systems, which will simply run it at the lower speed.",
    "2400": "2400 MHz (PC4-2400T) is the DDR4 speed used by many 6th–7th-generation Intel laptops and desktops. It runs at full speed in those machines and slower in older DDR4 systems that top out at 2133 MHz.",
    "2666": "2666 MHz (PC4-2666V) is the standard DDR4 speed for 8th–9th-generation Intel systems. In older 2400 MHz machines it works, running at 2400 MHz.",
    "3200": "3200 MHz (PC4-3200AA) is the fastest mainstream DDR4 speed, standard on 10th–11th-generation Intel and many AMD Ryzen systems. It is backward-compatible with 2400 and 2666 MHz machines, so it is the most flexible DDR4 choice.",
}


def ram_section(prod, ctx):
    n = prod["name"]
    mcap = re.search(r"(\d+)\s*GB", n, re.I)
    cap = int(mcap.group(1)) if mcap else 16
    speed = next((s for s in RAM_SPEED if s in n), None)
    laptop = "laptop" in n.lower()
    gaming = "gaming" in n.lower() or "rgb" in n.lower()
    gen = "DDR3" if re.search(r"ddr3|1333|1600", n, re.I) else "DDR4"
    out = [h2(f"What does {cap} GB of {gen} {'laptop' if laptop else 'desktop'} RAM mean for you?") if mcap else
           h2("How much gaming RAM do you need?")]
    text, who = RAM_CAP.get(cap, RAM_CAP[8])
    out.append(p(text))
    out.append(ul(who))
    if speed:
        out.append(h2(f"About the {speed} MHz speed"))
        out.append(p(RAM_SPEED[speed]))
    out.append(h2("Laptop SODIMM or desktop DIMM?" if not gaming else "Gaming RAM with RGB lighting"))
    if gaming:
        out.append(p("Gaming RAM uses taller heat spreaders to stay cool during long sessions, and RGB lighting that "
                     "can be synchronised with your motherboard's lighting software. It fits desktop DIMM slots; check "
                     "clearance under large CPU coolers. Install in matched pairs for dual-channel performance."))
    elif laptop:
        out.append(p(f"This is a SODIMM (small outline) module, about 67 mm long, made for laptops, mini PCs and some "
                     f"all-in-ones. It will not fit a standard desktop slot. Laptops usually have one or two slots; "
                     f"some thin models have one stick soldered and one free slot, so adding this {cap} GB module "
                     "alongside the soldered memory is a common upgrade."))
    else:
        out.append(p(f"This is a full-size DIMM module (about 133 mm long) for desktop towers, small form factor PCs "
                     f"and workstations. Most office desktops have two to four slots, so you can add this {cap} GB "
                     "module next to existing memory or replace smaller sticks entirely. It will not fit laptops."))
    pair = next((x for x in ctx["by_cat"].get("ram", []) if x["slug"] != prod["slug"]
                 and re.search(rf"\b{cap}\s*GB", x["name"], re.I) and gen.lower() in x["name"].lower()
                 and ("laptop" in x["name"].lower()) == laptop), None)
    if pair:
        out.append(p(f"Need the {'other speed' if speed else 'matching'} version? We also stock the "
                     f"<a href=\"/product/{pair['slug']}\">{pair['name']}</a> at {money(pair['price'])}."))
    return out


# ---------------- Storage ----------------
STORAGE_CAP = {
    "128GB": ("128 GB holds Windows, Office and a few essential programs, with limited room for files. It suits a "
              "boot drive in a desktop with a separate hard disk, a POS terminal, or a basic office machine that saves "
              "work to the cloud.", "About 20,000 photos, or roughly 30 hours of HD video, after Windows is installed"),
    "256GB": ("256 GB is the minimum we recommend for a laptop's main drive. It fits Windows, Office, common software "
              "and a reasonable collection of documents and photos for students and office users.",
              "About 50,000 photos, or roughly 60 hours of HD video, after Windows"),
    "512GB": ("512 GB is the sweet spot for most users: enough for Windows, all your programs, years of documents and "
              "a large photo library, plus a few games or video projects.",
              "About 120,000 photos, or 150+ hours of HD video, after Windows"),
    "1TB": ("1 TB suits creators, gamers and professionals who keep large files locally: video projects, game "
            "libraries, CAD models and big photo collections, with plenty of room left.",
            "About 250,000 photos, or 300+ hours of HD video, after Windows"),
    "500GB": ("500 GB of hard disk space is a practical amount for documents, music and photos, or for CCTV recording "
              "on small DVRs.", "About 4–7 days of continuous recording for a 4-camera 1080p DVR, depending on settings"),
}


def storage_section(prod, ctx):
    n = prod["name"]
    m = re.search(r"(\d+)\s*(GB|TB)", n, re.I)
    if not m:
        return []
    cap = (m.group(1) + m.group(2).upper()).replace("1000GB", "1TB")
    text, fits = STORAGE_CAP.get(cap, (None, None))
    if not text:
        return []
    out = [h2(f"Is {cap} enough for you?"), p(text),
           table(["Capacity", "Roughly holds"], [(cap, fits)])]
    others = sorted({(re.search(r"(\d+)\s*(GB|TB)", x["name"], re.I).group(0).upper().replace(" ", ""), x["slug"], x["price"])
                     for x in ctx["by_cat"].get("storage", []) if re.search(r"(\d+)\s*(GB|TB)", x["name"], re.I)
                     and x["slug"] != prod["slug"] and _same_form(x["name"], n)}, key=lambda t: t[2])
    if others:
        out.append(p("Other capacities in the same form factor: " + ", ".join(
            f"<a href=\"/product/{s}\">{c}</a> ({money(pr)})" for c, s, pr in others[:4]) + "."))
    return out


def _same_form(a, b):
    def form(x):
        x = x.lower()
        for k in ("msata", "2242", "2230", "nvme", "2.5", "laptop", "desktop", "2280"):
            if k in x:
                return k
        return "other"
    return form(a) == form(b)


# ---------------- Monitors ----------------
MON_SIZE = {
    "17": ("A 17-inch monitor (usually 1280×1024, 5:4 shape) is compact and very affordable, popular for CCTV "
           "viewing, POS back offices, reception desks and cyber cafés where desk space is limited.",
           "Viewing distance about 50–60 cm"),
    "19": ("A 19-inch widescreen (1440×900) monitor gives noticeably more width than a 17-inch for side-by-side "
           "windows, while still fitting small desks. It's a reliable budget office screen.",
           "Viewing distance about 55–65 cm"),
    "23.8": ("A 23.8-inch Full HD monitor (often sold as 24-inch) is today's standard office size: sharp text at "
             "1920×1080, room for two documents side by side and comfortable for all-day work.",
             "Viewing distance about 60–75 cm"),
    "24": ("A 24-inch edge-to-edge Full HD monitor gives a modern, almost borderless look, perfect for dual-monitor "
           "setups because the thin bezels leave only a small gap between screens.",
           "Viewing distance about 60–75 cm"),
    "27": ("A 27-inch Full HD monitor gives a big, immersive picture for multitasking, design review, entertainment "
           "and anyone who prefers larger text at a comfortable distance.",
           "Viewing distance about 70–90 cm"),
}


def monitor_section(prod, ctx):
    n = prod["name"]
    m = re.search(r"(23\.8|\d{2})\s*(?:-|\s)?(?:inch|″|\")", n, re.I)
    size = m.group(1) if m else None
    if size not in MON_SIZE:
        return []
    text, dist = MON_SIZE[size]
    brand = prod["brand"]
    out = [h2(f"Why a {size}-inch screen?"), p(text), p(f"Ergonomic tip: {dist}. Set the top of the screen at or slightly below eye level.")]
    if prod["condition"] == "refurbished":
        out.append(p(f"These are ex-corporate {brand} monitors: business models built to run all day in offices for "
                     "years. Each unit is checked for dead pixels, backlight bleed, stand stability and working inputs "
                     "before it's listed, and any light cosmetic marks are disclosed."))
    else:
        out.append(p(f"This is a brand-new {brand} monitor with full warranty, ideal if you want the latest panel "
                     "technology, slim bezels and HDMI connectivity out of the box."))
    return out


# ---------------- Model notes (printers & others) ----------------
MODEL_NOTES = {
    "g2410": "The PIXMA G2410 is Canon's simplest ink-tank all-in-one: print, scan and copy over USB. Choose it if you print from one computer and want the lowest purchase price in the G series.",
    "g2430": "The PIXMA G2430 is a refreshed USB ink-tank all-in-one in Canon's G series, with print, scan and copy, aimed at homes and small offices that print from one computer.",
    "g2470": "The PIXMA G2470 adds a more compact, refreshed design to Canon's USB ink-tank line, with print, scan and copy for home and small-office use.",
    "g3410": "The PIXMA G3410 adds Wi-Fi to Canon's ink-tank all-in-one, so phones and several laptops can print wirelessly. That makes it a better fit for families, shared offices and cyber cafés.",
    "l3210": "The EcoTank L3210 is Epson's entry USB ink-tank all-in-one (print, scan, copy), a favourite for schools and home printing on a budget.",
    "l3250": "The EcoTank L3250 adds Wi-Fi and phone printing (Epson Smart Panel app) to the L3210's design, so the whole household or office can print wirelessly.",
    "l6550": "The EcoTank L6550 is a business-class colour ink tank with Wi-Fi, automatic duplex printing and an automatic document feeder (ADF) for multi-page scanning and copying, built for busy offices.",
    "l6570": "The EcoTank L6570 adds fax and more office features to Epson's duplex Wi-Fi ink-tank range, with an ADF for multi-page copying and scanning: a full office MFP with very low running costs.",
    "l8100": "The Epson L8100 is a six-colour photo ink-tank printer designed for high-quality photo prints, borderless printing and CD/DVD printing, ideal for photo studios and creatives.",
    "smart tank 580": "The HP Smart Tank 580 is HP's Wi-Fi ink-tank all-in-one with print, scan and copy, set up easily with the HP Smart app on phones.",
    "smart tank 581": "The HP Smart Tank 581 is the wireless variant of HP's Smart Tank all-in-one, with easy phone setup via HP Smart and low-cost refill bottles.",
    "m111w": "The HP LaserJet M111w is a compact Wi-Fi mono laser printer, ideal for home offices and small businesses that print black documents.",
    "4003dn": "The HP LaserJet Pro 4003dn is a fast, network-ready mono laser with automatic duplex printing, built for busy offices and shared printing.",
    "lbp6030": "The Canon i-SENSYS LBP6030B is a compact, affordable mono laser printer for USB printing of documents at home or in small offices.",
    "mf3010": "The Canon i-SENSYS MF3010 is a compact mono laser all-in-one (print, scan, copy), a long-time favourite with small offices and cyber cafés.",
    "lbp226": "This Canon mono laser printer adds network and wireless connectivity plus automatic duplex for faster, paper-saving office printing.",
    "deskjet ink advantage 2875": "The HP DeskJet Ink Advantage 2875 is a compact wireless all-in-one with affordable 'Ink Advantage' cartridges, suited to light home printing.",
    "lq-350": "The Epson LQ-350 is a 24-pin dot matrix printer, producing sharper text than 9-pin models, which is ideal for official invoices and forms.",
    "lx-350": "The Epson LX-350 is a 9-pin dot matrix workhorse: fast, rugged and very cheap to run for high-volume multi-part forms.",
    "c270": "The Logitech C270 is a simple, reliable 720p HD webcam with a built-in mic, the go-to budget choice for video calls.",
    "c505e": "The Logitech C505e is a business 720p webcam with a long-range mic and a long USB cable, designed for office video meetings.",
    "c920": "The Logitech C920 is the classic 1080p Full HD webcam with stereo mics and autofocus, the most popular upgrade for professionals and streamers.",
    "c922": "The Logitech C922 is tuned for streaming, with Full HD video, better low-light handling and background-friendly features for creators.",
    "c925e": "The Logitech C925e is a business 1080p webcam with a privacy shutter and certification for leading meeting platforms.",
    "c930e": "The Logitech C930e is Logitech's premium business 1080p webcam with a wide 90° field of view for small meeting rooms.",
    "r400": "The Logitech R400 is a straightforward wireless presenter with a red laser pointer and about 10 m range.",
    "r500s": "The Logitech R500s connects by USB receiver or Bluetooth, so it works with laptops without free USB ports, and adds a red laser pointer.",
}


def model_note(prod):
    n = prod["name"].lower()
    for k, v in MODEL_NOTES.items():
        if k in n:
            return [h2(f"About this model"), p(v)]
    return []


def variant_sections(prod, t, ctx):
    key = t["key"]
    out = []
    if key == "ram":
        out += ram_section(prod, ctx)
    elif key in ("nvme", "m2sata", "msata", "sata25", "hdd"):
        out += storage_section(prod, ctx)
    elif key == "monitor":
        out += monitor_section(prod, ctx)
    out += model_note(prod)
    return out
