"""Long-form SEO/AEO content for laptops, desktops, workstations and servers."""
import re

from .common import (pick, money, link_cat, closing_sections, faq, h2, p, ul, table, similar_products,
                     cheapest_in, ORDER_FAQS)
from .kb_computers import (GEN, SUFFIX, TIER_TEXT, GPU_TIER, TASKS, cpu_info, cores_for, line_for, ram_gen_for,
                           score, task_verdict)

DESKTOP_CATS = {"desktops"}


def short_title(name):
    """A shorter, human version of the product name for headings (model + key spec)."""
    t = re.split(r"[,(–]| with | Core| core| Intel| i[3579][ -]| Ci[3579]", name)[0].strip()
    if len(t.split()) <= 2:
        m = re.search(r"(?:Core[\s-]*)?(i[3579])[\s-]*(\d{1,2}(?:th|rd|nd) Gen)?", name, re.I)
        if m:
            t = f"{t} {m.group(1).lower()}" + (f" {m.group(2)}" if m.group(2) else "")
    return t if len(t) >= 8 else name[:60]


def write(prod, ctx):
    name, specs, cat, cond = prod["name"], prod["specs"], prod["category"], prod["condition"]
    is_desktop = cat in DESKTOP_CATS
    is_server = "proliant" in name.lower() or "server" in name.lower()
    kind = "server" if is_server else ("workstation" if "workstation" in name.lower() or "precision" in name.lower()
                                       or "z440" in name.lower() or "z820" in name.lower() else
                                       "desktop" if is_desktop else "laptop")
    cond_word = {"refurbished": "refurbished", "new": "brand-new", "ex-uk": "ex-UK"}[cond]
    if "slightly used" in name.lower():
        cond_word = "slightly used"
    st = short_title(name)
    info = cpu_info(specs.get("cpu"), name)
    line = line_for(name)
    sc = score(info, specs, name)
    gpu = specs.get("gpu")
    ram = specs.get("ram")
    storage = specs.get("storage")
    price = prod["price"]
    warranty = prod["warranty_months"]
    out = []

    # ---------- Intro (quick answer) ----------
    best_for = best_for_list(sc, gpu, kind, line)
    out.append(p(
        f"The <strong>{name}</strong> is a {cond_word} {kind} available at {ctx['site']} in Nairobi for "
        f"<strong>{money(price)}</strong>"
        + (f", with a {warranty}-month warranty" if warranty else "")
        + f". It is best suited to {best_for[0].lower()}"
        + (f" and {best_for[1].lower()}" if len(best_for) > 1 else "")
        + ". This page explains exactly what it can and cannot do, how it compares with similar machines in our "
          "shop, and what to check before you buy."))

    facts = [("Price", money(price)), ("Condition", cond_word.capitalize())]
    labels = {"cpu": "Processor", "ram": "Memory (RAM)", "storage": "Storage", "gpu": "Graphics",
              "display": "Screen size", "touchscreen": "Touchscreen", "form_factor": "Design", "os": "Operating system"}
    for k, lab in labels.items():
        if specs.get(k):
            facts.append((lab, specs[k]))
    facts.append(("Warranty", f"{warranty} months" if warranty else "Seller support"))
    facts.append(("Best for", ", ".join(best_for)))
    out.append(h2(f"{st}: key facts"))
    out.append(table(["Feature", "Details"], facts))

    # ---------- Pros & cons ----------
    pros, cons = pros_cons(prod, info, line, sc, kind)
    out.append(h2(f"{st}: pros and cons"))
    out.append(table(["Pros", "Cons"], [(pros[i] if i < len(pros) else "", cons[i] if i < len(cons) else "")
                                        for i in range(max(len(pros), len(cons)))]))

    # ---------- Who it's for ----------
    out.append(h2(f"Who should buy the {st}?"))
    who = [
        p(pick(name, [
            f"We recommend this {kind} to {best_for[0].lower()}.",
            f"This {kind} is a good fit for {best_for[0].lower()}.",
            f"In our experience selling this {kind}, it suits {best_for[0].lower()} best.",
        ]) + " " + who_detail(sc, gpu, kind, cond, price)),
        ul([f"<strong>{b}</strong>" for b in best_for]),
    ]
    out += who
    if sc <= 4 and not gpu:
        out.append(p(f"If you need to edit video, run AutoCAD 3D or play modern games, look instead at our "
                     f"{link_cat('gaming-laptops', 'gaming laptops')} or "
                     f"{link_cat('refurbished-laptops', 'higher-spec refurbished laptops')} such as the HP ZBook range."))

    # ---------- Line background ----------
    if line:
        out.append(h2(f"About the {line['title']} range"))
        out.append(p(f"<strong>{line['title']}</strong>: {line['text']}"))
        out.append(p(pick(name + "line", [
            "Business and premium lines like this are designed to last several years of daily use, which is why "
            "they remain dependable long after their first owner, and why spare parts such as batteries, keyboards "
            "and chargers are easy to find in Nairobi.",
            "Because this range sold in large numbers to companies and institutions, replacement parts, chargers "
            "and batteries are widely available in Kenya, which keeps long-term ownership costs low.",
            "One advantage of buying a well-known range is after-sales support: technicians in Nairobi know these "
            "machines well, and parts are easy to source if you ever need a repair.",
        ])))

    # ---------- Processor ----------
    cpu = specs.get("cpu")
    if cpu:
        out.append(h2(f"Processor: {cpu}"))
        bits = []
        tier = info.get("tier")
        if tier in TIER_TEXT:
            bits.append(TIER_TEXT[tier] + ".")
        gen = info.get("gen")
        if gen in GEN:
            year, code, note = GEN[gen]
            bits.append(f"This is {article(ordinal(gen))} {ordinal(gen)}-generation Intel chip (codename {code}, launched {year}), "
                        f"{note}.")
        if info.get("model"):
            suf = info.get("suffix") or ""
            if suf in SUFFIX:
                bits.append(f"The '{suf or 'no suffix'}' in the model number {info['model']} marks "
                            f"{SUFFIX[suf]}.")
        cores = cores_for(info, kind != "laptop")
        if cores:
            bits.append(f"Chips in this class typically have {cores}, which determines how well the machine "
                        f"copes when you run several programs at once.")
        bits.append(cpu_real_world(sc, tier, gen))
        out.append(p(" ".join(bits)))

    # ---------- Memory & storage ----------
    out.append(h2("Memory (RAM) and storage"))
    out.append(p(ram_text(ram, kind)))
    out.append(p(storage_text(storage, kind)))

    # ---------- Graphics ----------
    out.append(h2("Graphics"))
    out.append(p(graphics_text(gpu, info, kind)))

    # ---------- Display / design ----------
    disp = specs.get("display")
    design_bits = []
    if disp:
        design_bits.append(display_text(disp, specs))
    if specs.get("form_factor"):
        design_bits.append("As a 2-in-1 convertible, the screen folds back into tent, stand and tablet modes, which "
                           "is useful for presentations, reading, drawing and taking handwritten notes.")
    if specs.get("touchscreen") and not specs.get("form_factor"):
        design_bits.append("The touchscreen lets you scroll, zoom and sign documents with a finger or stylus.")
    if kind in ("desktop", "workstation", "server"):
        design_bits.append(desktop_design_text(name, kind))
    if design_bits:
        out.append(h2("Display and design" if kind == "laptop" else "Design and connectivity"))
        out.append(p(" ".join(design_bits)))

    # ---------- What can it run ----------
    out.append(h2(f"What can the {st} run?"))
    out.append(p("Here is what this class of hardware typically handles, based on its processor, memory, storage and "
                 "graphics. Use it as a guide to whether this machine fits your work:"))
    out.append(table(["Task", "Verdict"], [(t, task_verdict(sc, need, bool(gpu))) for t, need in TASKS]))

    # ---------- Software / Windows ----------
    out.append(h2("Windows and software"))
    out.append(p(windows_text(info, specs, cond)))

    # ---------- Condition / in the box ----------
    if cond == "refurbished" or "slightly used" in name.lower():
        out.append(h2("How we test and prepare it"))
        out.append(p(f"Every {cond_word} {kind} we sell goes through our inspection before it is listed. We check "
                     "and, where needed, fix or replace:"))
        checks = ["Battery health (we report the percentage; replaced if weak)" if kind == "laptop" else
                  "Power supply and fans under load",
                  "Screen for dead pixels, bright spots and backlight bleed" if kind == "laptop" else
                  "All video outputs (VGA/DisplayPort/HDMI)",
                  "Every keyboard key, touchpad and TrackPoint" if kind == "laptop" else "All USB, audio and network ports",
                  "Storage health (SMART) and read/write speed", "RAM stress test",
                  "Wi-Fi, Bluetooth and Ethernet", "Temperatures and fan noise under load",
                  "Clean Windows installation and activation status", "Physical clean of keyboard, vents and casing"]
        out.append(ul(checks))
        out.append(p("Light cosmetic marks are normal on used business machines and do not affect performance. If "
                     "you'd like to see the exact unit before paying, visit our shop or ask for photos on WhatsApp."))
    else:
        out.append(h2("Brand-new: what you get"))
        out.append(p(f"This {kind} is brand new and sealed, with the original charger and documentation. It carries "
                     f"a {warranty}-month warranty. Note that the operating system is listed in the specifications: "
                     "models marked FreeDOS/DOS ship without Windows, so budget for a Windows licence or ask us to "
                     "install one for you."))

    # ---------- Upgrades ----------
    out.append(h2("Upgrade options"))
    out.append(p(upgrade_text(info, line, name, specs, kind, ctx)))

    # ---------- Comparisons ----------
    sims = similar_products(prod, ctx, n=3)
    if sims:
        out.append(h2(f"How the {st} compares with similar models"))
        out.append(p("Not sure this is the right one? Here is how it stacks up against similar machines in our shop "
                     "right now:"))
        rows = [(f"<a href=\"/product/{s['slug']}\">{s['name']}</a>", money(s["price"]), s["specs"].get("cpu", "–"),
                 s["specs"].get("ram", "–"), s["specs"].get("storage", "–")) for s in [prod] + sims]
        out.append(table(["Model", "Price", "Processor", "RAM", "Storage"], rows))
        out.append(p(compare_text(prod, sims)))

    # ---------- Buying checklist ----------
    out.append(h2("Buying checklist"))
    out.append(ul(checklist(kind, cond, specs, line)))

    out += closing_sections(prod, ctx)

    faqs = computer_faqs(prod, info, line, sc, kind, ctx)
    return {"html": "".join(out), "faqs": faqs, "best_for": best_for}


# ----------------------------------------------------------------------------------------------------------

VERDICT_SENTENCE = {
    "Excellent": "Yes, comfortably.",
    "Good": "Yes. It runs AutoCAD 2D drafting and Photoshop well for everyday projects.",
    "Possible, with patience": "It can, but large files will feel slow; it is better suited to lighter work.",
    "Light projects only": "Yes, for light projects.",
    "Not recommended": "Not really. Choose a newer, higher-spec machine for design software.",
}


def article(word):
    return "an" if str(word)[:1].lower() in "aeio8" or str(word).startswith(("11", "18")) else "a"


def ordinal(n):
    return f"{n}{'st' if n % 10 == 1 and n != 11 else 'nd' if n % 10 == 2 and n != 12 else 'rd' if n % 10 == 3 and n != 13 else 'th'}"


def best_for_list(sc, gpu, kind, line):
    if kind == "server":
        return ["Small-office file and print sharing", "Accounting and ERP databases", "Backups and internal apps"]
    if gpu:
        if "zbook" in (line or {}).get("title", "").lower() or kind == "workstation":
            return ["Engineers and architects (AutoCAD, Revit)", "GIS and data analysis", "Video editing"]
        return ["Gamers", "Video editors and 3D artists", "Engineering students"]
    if kind == "workstation":
        return ["Engineering and design software", "Heavy multitasking", "Rendering and computation"]
    if sc >= 7:
        return ["Professionals and managers", "Programmers", "Heavy multitaskers"]
    if sc >= 5:
        return ["University students", "Office and business users", "Remote workers"]
    if sc >= 3:
        return ["Students on a budget", "Office work and browsing", "Cyber cafés and front desks"]
    return ["Basic typing and browsing", "Children's schoolwork", "A backup or first computer"]


def who_detail(sc, gpu, kind, cond, price):
    if gpu:
        return ("The dedicated NVIDIA graphics card is what sets it apart: it accelerates games, video exports, "
                "3D viewports and GPU-assisted software far beyond what integrated graphics can manage.")
    if sc >= 7:
        return ("There is enough processing power and memory to keep dozens of browser tabs, Office, Teams and "
                "development tools open together without slowing down.")
    if sc >= 5:
        return ("It handles a full day of documents, spreadsheets, research and video calls comfortably, and "
                "boots quickly thanks to its solid-state storage.")
    if sc >= 3:
        return (f"At {money(price)} it is an affordable way to get a dependable machine for typing, browsing, "
                "email and online forms such as eCitizen and KRA iTax.")
    return ("It is a low-cost machine for light tasks. Keep expectations modest: it is best with one or two "
            "programs open at a time.")


def cpu_real_world(sc, tier, gen):
    if tier == "xeon":
        return ("In practice, Xeon systems shine in software that uses many threads at once (rendering, compiling, "
                "simulation, virtual machines and databases) and are built for long, continuous workloads.")
    if sc >= 8:
        return "In everyday use this is a fast processor that will stay capable for years."
    if sc >= 5:
        return ("In everyday use it feels quick for office, school and business software, and it handles video calls "
                "with background apps open.")
    return ("In everyday use it is comfortable for documents, email and browsing, but expect slower performance in "
            "heavy software or with many browser tabs open.")


def ram_text(ram, kind):
    if not ram:
        return (f"The memory configuration for this {kind} can vary by unit, so confirm the exact RAM with us before "
                "buying. For Windows 10 or 11 we recommend at least 8 GB.")
    gb = int(re.sub(r"\D", "", ram))
    if gb <= 4:
        return (f"It comes with {ram} of RAM. That is enough for one or two programs, but Windows 10/11 with a "
                "browser and Office open will feel slow. We strongly recommend upgrading to 8 GB, which we can do "
                f"at purchase. See our {link_cat('ram', 'RAM upgrades')}.")
    if gb <= 8:
        return (f"It has {ram} of RAM, the practical minimum for Windows 10 and 11 today. It runs Office, a browser "
                "with 10–15 tabs and a Zoom call comfortably. If you use Photoshop, large Excel models or many apps "
                "at once, 16 GB will feel noticeably smoother.")
    if gb <= 16:
        return (f"With {ram} of RAM it multitasks comfortably: dozens of browser tabs, Office, Teams, and creative "
                "or development tools can all stay open at once. 16 GB is the sweet spot for professionals and "
                "students in technical courses.")
    return (f"{ram} of RAM is plenty for heavy professional work: virtual machines, large datasets, 4K video "
            "timelines and big 3D scenes, with headroom for years.")


def storage_text(storage, kind):
    if not storage:
        return ("Storage varies by unit; confirm the exact drive with us. We recommend an SSD for any computer you "
                "use daily, because it makes start-up and loading several times faster.")
    is_ssd = "SSD" in storage
    size = storage.split()[0]
    if is_ssd:
        return (f"Storage is a {size} solid-state drive (SSD). An SSD has no moving parts, so Windows starts in "
                "seconds, programs open quickly and the drive is far more resistant to knocks than a hard disk. "
                + ("At this size you can store your documents, software and a large photo library; add an external "
                   "drive or cloud storage for big video collections." if size not in ("128GB",) else
                   "128 GB is tight once Windows updates and Office are installed, so plan to keep large files on "
                   "cloud storage or an external drive, or ask us about a bigger SSD."))
    return (f"Storage is a {size} hard disk drive (HDD). It gives lots of space for files at a low price, but a "
            "hard disk is much slower than an SSD: start-up and opening programs take noticeably longer. Upgrading "
            f"to an SSD is the single best improvement you can make. See our {link_cat('storage', 'SSD range')}, "
            "and we install and transfer your data for free when you buy the drive from us.")


def graphics_text(gpu, info, kind):
    if gpu:
        m = re.search(r"RTX (\d{4})", gpu)
        tier = GPU_TIER.get(m.group(1)) if m else None
        base = f"Graphics are handled by a dedicated {gpu}"
        if tier:
            base += f", {tier}."
        else:
            base += (", a professional-grade chip that accelerates CAD viewports, GIS rendering, video effects and "
                     "GPU-assisted software, with its own memory so it doesn't eat into your system RAM.")
        return base + (" Dedicated graphics also drive external monitors smoothly, and NVIDIA's encoders speed up "
                       "video exports and streaming.")
    gen = info.get("gen") or 0
    tier = info.get("tier")
    if tier == "ultra":
        return ("It uses built-in Intel Arc graphics, which are strong for integrated graphics: smooth 4K video, "
                "photo editing and light games, plus AI acceleration from the built-in NPU.")
    if tier == "xeon":
        return ("Graphics depend on the card installed in this unit; workstations accept full-size professional "
                "or gaming graphics cards if you need GPU acceleration. Ask us which card is fitted.")
    if gen >= 11 and info.get("suffix", "").startswith("G7") or (gen >= 11 and tier in ("i5", "i7")):
        return ("It uses Intel Iris Xe integrated graphics, a big step up from older Intel graphics: smooth HD and "
                "4K video, two external monitors, light photo and video editing, and older or lighter games.")
    return ("It uses Intel integrated graphics, which handle HD video streaming, presentations, online classes and "
            "external monitors well. It is not designed for modern 3D games, heavy video editing or 3D CAD.")


def display_text(disp, specs):
    size = float(disp.rstrip('"'))
    if size < 13:
        t = (f"The {disp} screen keeps the machine very compact and light: easy to carry around campus or between "
             "meetings, though small for long spreadsheet sessions (pair it with an external monitor at your desk).")
    elif size < 14.5:
        t = (f"The {disp} screen is the most popular business size: big enough to work comfortably on all day, "
             "small enough to fit in any bag.")
    elif size < 16.5:
        t = (f"The {disp} screen gives a large workspace, and many 15.6\" models include a number pad, which "
             "accountants and data-entry users appreciate.")
    else:
        t = f"The large {disp} screen gives you plenty of room for side-by-side windows."
    return t


def desktop_design_text(name, kind):
    n = name.lower()
    if "mini" in n or "tiny" in n or "z2 g4" in n:
        return ("The mini form factor is tiny, can mount behind a monitor with a VESA bracket, and uses little "
                "power, which is ideal for front desks, POS stations and small offices.")
    if "sff" in n or "small form" in n:
        return ("The small form factor (SFF) case takes up little desk space and uses less electricity than a full "
                "tower, which is why SFF desktops are popular in cyber cafés, schools and offices.")
    if "all in one" in n:
        return "The all-in-one design means one power cable and a clean desk: the PC is inside the monitor."
    if kind == "server":
        return ("As a tower server it is designed for 24/7 operation, with room for multiple hard drives for "
                "storage and backups.")
    if kind == "workstation":
        return ("The tower chassis has room for extra drives, more memory and full-size graphics cards, so you can "
                "grow the machine as your workload grows.")
    return ("The tower or micro-tower case is easy to open for upgrades and repairs, and has plenty of USB ports "
            "for keyboards, mice, printers and flash drives. Add any monitor from our "
            + link_cat("monitors", "monitors range") + ".")


def windows_text(info, specs, cond):
    gen = info.get("gen")
    os_ = specs.get("os", "")
    if "FreeDOS" in os_ or "No Windows" in os_:
        return ("This model ships without Windows (FreeDOS), which is how many new business laptops are sold in "
                "Kenya to keep the price down. You will need a Windows licence; we can install genuine Windows 11 "
                "and Microsoft Office for you at an extra cost, so the machine is ready to use when you collect it.")
    if info.get("tier") in ("ultra",) or (gen and gen >= 8):
        return ("This processor generation is officially supported by Windows 11, so you will keep receiving "
                "Microsoft security updates. Units we sell come with Windows installed and activated; we can also "
                "set up Microsoft Office, antivirus and your email before collection.")
    if info.get("tier") == "xeon":
        return ("Workstations and servers can run Windows 10/11 Pro for Workstations, Windows Server or Linux "
                "depending on your software. Tell us your use and we will install the right system.")
    return ("Processors of this age are not on Microsoft's official Windows 11 list. They run Windows 10 well, "
            "but Microsoft ended free Windows 10 support in October 2025, so for a daily work machine consider "
            "a newer generation (8th Gen or later) or Microsoft's Extended Security Updates. For basic home use, "
            "browsing and typing they remain perfectly usable.")


def upgrade_text(info, line, name, specs, kind, ctx):
    rg = ram_gen_for(info, name)
    parts = []
    if line and line["soldered"]:
        parts.append("On this slim design, memory is soldered to the motherboard on most units, so it cannot be "
                     "upgraded later; buy the RAM you need now.")
    elif rg and "not upgradable" not in rg:
        gb_now = specs.get("ram", "")
        stick = "SODIMM (laptop)" if kind == "laptop" else "DIMM (desktop)"
        cheapest = cheapest_in(ctx, "ram", must=[rg.split()[0].replace("L", "")], kind_word="Laptop" if kind == "laptop" else "Desktop")
        parts.append(f"The memory type is most likely {rg} {stick}. "
                     + (f"You can add more RAM: our {rg.split()[0]} {'laptop' if kind == 'laptop' else 'desktop'} "
                        f"RAM starts from {money(cheapest)}. " if cheapest else "")
                     + (f"Going from {gb_now} to 16 GB is the most noticeable upgrade for multitasking." if gb_now
                        and gb_now in ("4GB", "8GB") else ""))
    elif rg:
        parts.append("Memory is built into the processor package on this platform and cannot be upgraded.")
    st = specs.get("storage", "")
    if "HDD" in st:
        cheapest = cheapest_in(ctx, "storage", must=["2.5" if kind == "laptop" else "SSD"])
        parts.append("Swapping the hard disk for an SSD will transform start-up and loading times"
                     + (f"; SSDs start from {money(cheapest)} in our shop" if cheapest else "") + ".")
    elif st:
        parts.append(f"The {st} can be swapped for a larger SSD if you run out of space; we clone your data for "
                     "free when you buy the new drive from us.")
    if kind == "laptop":
        parts.append("A replacement battery or an original charger can be sourced for this model if needed.")
    parts.append(f"See {link_cat('ram', 'RAM')} and {link_cat('storage', 'SSDs')} for compatible parts.")
    return " ".join(parts)


def compare_text(prod, sims):
    lines = []
    for s in sims:
        diff = s["price"] - prod["price"]
        d = money(abs(diff))
        if diff > 0:
            lines.append(f"The {s['name']} costs {d} more"
                         + (f" and has {s['specs']['ram']} RAM" if s["specs"].get("ram") and s["specs"].get("ram") != prod["specs"].get("ram") else "")
                         + ".")
        elif diff < 0:
            lines.append(f"The {s['name']} is {d} cheaper"
                         + (f", with {article(s['specs']['cpu'])} {s['specs']['cpu']}" if s["specs"].get("cpu") and s["specs"].get("cpu") != prod["specs"].get("cpu") else "")
                         + ".")
        else:
            lines.append(f"The {s['name']} is the same price, so compare the specs above.")
    lines.append("Ask us on WhatsApp if you'd like a side-by-side recommendation for your exact use.")
    return " ".join(lines)


def checklist(kind, cond, specs, line):
    c = []
    if kind == "laptop":
        c.append("Decide on screen size first: 12–13\" for carrying all day, 14\" as a balance, 15.6\" for a big screen and number pad.")
    c.append("Get at least 8 GB RAM and an SSD for Windows 10/11; 16 GB for creative, technical or heavy multitasking work.")
    c.append("Prefer 8th-generation Intel or newer if you want official Windows 11 support.")
    if cond == "refurbished":
        c.append("Ask for the battery health percentage and test the keyboard, screen and ports before paying.")
        c.append("Make sure the warranty is written on your receipt.")
    else:
        c.append("Check whether Windows is included (DOS models need a licence).")
    if specs.get("gpu"):
        c.append("For gaming laptops, check temperatures under load and keep the vents clear; use a cooling pad for long sessions.")
    c.append("Buy from a shop you can visit for after-sales support.")
    return c


def computer_faqs(prod, info, line, sc, kind, ctx):
    name, specs, price = prod["name"], prod["specs"], prod["price"]
    st = short_title(name)
    out = [faq(f"How much is the {st} in Kenya?",
               f"The {name} costs {money(price)} at {ctx['site']}"
               + (f", with a {prod['warranty_months']}-month warranty" if prod["warranty_months"] else "")
               + ". You can pay with M-Pesa online or in our Nairobi CBD shop.")]
    gen = info.get("gen")
    if gen:
        win11 = gen >= 8
        out.append(faq(f"Does the {st} support Windows 11?",
                       ("Yes. Its " + ordinal(gen) + "-generation Intel processor is on Microsoft's supported list for Windows 11.")
                       if win11 else
                       (f"Not officially. Its {ordinal(gen)}-generation processor is below Microsoft's Windows 11 "
                        "requirement, so it runs Windows 10. For long-term security updates, consider an 8th-gen or newer model.")))
    out.append(faq(f"Is the {st} good for students?",
                   ("Yes. It handles assignments, research, Zoom classes and Office comfortably."
                    if sc >= 4 else
                    "It is fine for typing, browsing and online classes, but for heavier software choose a model with "
                    "a newer processor and 8 GB+ RAM.")
                   + (" Its dedicated graphics also suit engineering, architecture and design courses." if specs.get("gpu") else "")))
    out.append(faq(f"Can the {st} run AutoCAD or Photoshop?",
                   VERDICT_SENTENCE[task_verdict(sc, 5, bool(specs.get("gpu")))] + " "
                   + ("Its dedicated graphics make it suitable for 3D work as well." if specs.get("gpu") else
                      "For 3D modelling and heavy rendering, a machine with dedicated NVIDIA graphics is better.")))
    if kind == "laptop":
        out.append(faq(f"Can I upgrade the RAM on the {st}?",
                       "On most units the memory is soldered, so it can't be upgraded; choose the RAM you need now."
                       if line and line["soldered"] else
                       "Yes, on most units you can add or replace the RAM module. We can fit it in-store for free "
                       "when you buy the RAM from us."))
    out += ORDER_FAQS(prod, ctx)
    return out


def pros_cons(prod, info, line, sc, kind):
    specs, price = prod["specs"], prod["price"]
    pros, cons = [], []
    ram = int(re.sub(r"\D", "", specs.get("ram", "0")) or 0)
    st = specs.get("storage", "")
    gen = info.get("gen") or 0
    if line and any(k in line["title"] for k in ("EliteBook", "ThinkPad", "Latitude", "ZBook", "ExpertBook", "ThinkBook",
                                                  "OptiPlex", "ProDesk", "EliteDesk", "ThinkCentre", "Precision", "Z")):
        pros.append("Business-grade build quality and easy repairs")
    if "SSD" in st:
        pros.append(f"Fast {st} storage")
    if "HDD" in st:
        cons.append("Hard disk is slow; an SSD upgrade is recommended")
    if ram >= 16:
        pros.append(f"{ram} GB RAM for heavy multitasking")
    elif ram and ram <= 4:
        cons.append("4 GB RAM is low for Windows 10/11")
    if gen >= 8 or info.get("tier") == "ultra":
        pros.append("Officially supports Windows 11")
    elif gen:
        cons.append(f"{ordinal(gen)}-gen processor isn't on the Windows 11 list")
    if specs.get("gpu"):
        pros.append("Dedicated NVIDIA graphics for games and 3D work")
    elif kind == "laptop":
        cons.append("No dedicated graphics for modern games or 3D")
    if specs.get("touchscreen") or specs.get("form_factor"):
        pros.append("Touchscreen" + (" and 360° hinge" if specs.get("form_factor") else ""))
    if "FreeDOS" in specs.get("os", "") or "No Windows" in specs.get("os", ""):
        cons.append("Ships without Windows (licence needed)")
    disp = specs.get("display")
    if disp:
        size = float(disp.rstrip('"'))
        if size <= 13.3 and kind == "laptop":
            pros.append("Compact and easy to carry")
            cons.append("Small screen for long spreadsheet work")
        elif size >= 15.6:
            pros.append("Large screen, often with number pad")
            cons.append("Heavier to carry daily")
    if line and line["soldered"]:
        cons.append("RAM usually soldered (not upgradable)")
    if prod["condition"] == "refurbished":
        pros.append(f"Costs far less than new; {prod['warranty_months']}-month warranty")
        cons.append("May show light cosmetic wear")
    else:
        pros.append(f"Brand new with {prod['warranty_months']}-month warranty")
    if kind == "laptop" and gen and gen <= 5:
        cons.append("Older battery technology; check battery health")
    if not cons:
        cons.append("Higher price than older-generation alternatives")
    return pros[:6], cons[:6]
