"""Knowledge base for laptops, desktops, workstations and servers.

All statements are general, well-established facts about processor generations and product lines.
Where a detail varies by exact configuration (e.g. core counts without a model number, soldered RAM),
the writer hedges with "typically" / "on most units" and invites the buyer to confirm with the shop.
"""
import re

# Intel Core generation -> (launch year, codename, typical notes)
GEN = {
    2: ("2011", "Sandy Bridge", "the first generation with integrated graphics on the same chip"),
    3: ("2012", "Ivy Bridge", "a refinement of the 2nd generation with better integrated graphics and USB 3.0 support"),
    4: ("2013", "Haswell", "the generation that brought a big jump in battery life for laptops"),
    5: ("2015", "Broadwell", "a die-shrink of Haswell focused on efficiency in thin laptops"),
    6: ("2015", "Skylake", "the first generation to use DDR4 memory widely and to support fast NVMe SSDs"),
    7: ("2016–2017", "Kaby Lake", "a refined Skylake with better video decoding for 4K streaming"),
    8: ("2017–2018", "Kaby Lake Refresh / Coffee Lake / Whiskey Lake",
        "the generation where laptop Core i5 and i7 chips doubled from two to four cores"),
    10: ("2019–2020", "Comet Lake / Ice Lake", "a mature, efficient generation with Wi-Fi 6 on many models"),
    11: ("2020–2021", "Tiger Lake", "the generation that introduced Intel Iris Xe graphics and Thunderbolt 4"),
    12: ("2022", "Alder Lake", "the first hybrid design with Performance-cores and Efficient-cores"),
    13: ("2023", "Raptor Lake", "a faster hybrid design with more Efficient-cores than the 12th generation"),
    14: ("2024", "Raptor Lake Refresh", "the top of Intel's hybrid Core line before the Core Ultra rebrand"),
}

SUFFIX = {
    "U": "a low-power (about 15 W) chip built for thin laptops, balancing performance with long battery life",
    "H": "a high-performance laptop chip (about 35–45 W) built for gaming, engineering and creative work",
    "HX": "a desktop-class laptop chip for maximum performance in gaming and workstation laptops",
    "G7": "a low-power laptop chip with the top Intel Iris Xe graphics configuration",
    "T": "a power-efficient desktop chip used in mini PCs",
    "": "a full-power desktop chip",
}

# (gen, tier, segment) -> typical cores/threads. segment: U (thin laptop), H (performance laptop), D (desktop)
CORES = {
    ("old", "i3", "U"): "2 cores / 4 threads", ("old", "i5", "U"): "2 cores / 4 threads",
    ("old", "i7", "U"): "2 cores / 4 threads",
    ("old", "i3", "D"): "2 cores / 4 threads", ("old", "i5", "D"): "4 cores / 4 threads",
    ("old", "i7", "D"): "4 cores / 8 threads",
    (8, "i5", "U"): "4 cores / 8 threads", (8, "i7", "U"): "4 cores / 8 threads",
    (8, "i5", "D"): "6 cores / 6 threads", (9, "i5", "D"): "6 cores / 6 threads",
    (10, "i3", "D"): "4 cores / 8 threads", (10, "i5", "U"): "4 cores / 8 threads",
    (10, "i7", "U"): "4 cores / 8 threads", (10, "i7", "D"): "8 cores / 16 threads",
    (10, "i7", "H"): "6 cores / 12 threads", (10, "i9", "H"): "8 cores / 16 threads",
    (11, "i5", "U"): "4 cores / 8 threads", (11, "i7", "U"): "4 cores / 8 threads",
    (11, "i5", "H"): "6 cores / 12 threads", (11, "i7", "H"): "8 cores / 16 threads",
    (12, "i3", "U"): "6 cores / 8 threads", (12, "i5", "U"): "10 cores / 12 threads",
    (12, "i7", "U"): "10 cores / 12 threads", (12, "i7", "H"): "14 cores / 20 threads",
    (12, "i7", "D"): "12 cores / 20 threads",
    (13, "i5", "U"): "10 cores / 12 threads", (13, "i7", "U"): "10 cores / 12 threads",
    (13, "i5", "H"): "8 cores / 12 threads", (13, "i7", "H"): "10 cores / 16 threads",
    (13, "i9", "H"): "up to 24 cores / 32 threads",
    (14, "i7", "H"): "up to 20 cores / 28 threads", (14, "i9", "H"): "up to 24 cores / 32 threads",
}

TIER_TEXT = {
    "i3": "Core i3 is Intel's entry tier: fine for documents, browsing and video calls, but it slows down with heavy multitasking",
    "i5": "Core i5 is the mainstream tier and the sweet spot for most buyers: quick for office work, browsing, online classes and light creative work",
    "i7": "Core i7 is the upper tier with higher clock speeds and, on many models, more cache, which helps with heavy spreadsheets, coding, photo editing and multitasking",
    "i9": "Core i9 is Intel's flagship tier, built for the heaviest gaming, 3D rendering and video work",
    "ultra": "Core Ultra is Intel's newest family with a built-in NPU (AI accelerator) and strong Intel Arc graphics, designed for long battery life and Windows AI features",
    "xeon": "Xeon is Intel's workstation and server processor family, designed to run 24/7 with support for large amounts of (often ECC) memory and many-threaded professional software",
    "celeron": "Celeron is Intel's budget processor family, suited to basic browsing, documents and learning apps rather than multitasking",
}

# Product lines: keyword -> (line name, description, soldered_ram_likely, built_for)
LINES = [
    ("elite x2", "HP Elite x2", "HP's business detachable: a Windows tablet with a click-on keyboard, aimed at professionals who want a tablet that runs full desktop software. It supports a pen on most units and uses a kickstand instead of a hinge.", True),
    ("x360 1030", "HP EliteBook x360 1030", "HP's premium 13-inch convertible business laptop. The 360-degree hinge lets it fold into tent, stand or tablet mode, and the aluminium chassis keeps it light (around 1.2–1.3 kg) for daily carrying.", True),
    ("x360 1040", "HP EliteBook x360 1040", "HP's 14-inch premium convertible: a larger-screen EliteBook that folds into a tablet. It combines a full-size business keyboard with touch and pen input, and is popular with managers and consultants who present often.", True),
    ("elitebook 1040", "HP EliteBook 1040", "HP's thin-and-light 14-inch flagship business laptop with an aluminium body, a quality keyboard and strong security features.", True),
    ("elitebook 8", "HP EliteBook 800 series", "HP's core business line (820 = 12.5\", 830 = 13.3\", 840 = 14\"). EliteBooks are built with metal chassis, spill-resistant keyboards and business security features such as HP Sure Start BIOS protection, and are tested to tough military-standard durability specs on most generations.", False),
    ("elitebook", "HP EliteBook", "HP's premium business laptop line, built with metal chassis, spill-resistant keyboards and business security features.", False),
    ("probook", "HP ProBook", "HP's mid-range business laptop line: durable, easy to service and priced below the EliteBook series.", False),
    ("zbook firefly", "HP ZBook Firefly", "HP's thin-and-light mobile workstation. It looks like an ultrabook but carries a professional NVIDIA graphics chip and ISV-certified drivers for engineering and design software.", False),
    ("zbook power", "HP ZBook Power", "HP's 15.6-inch value mobile workstation, built for AutoCAD, Revit, SolidWorks, ArcGIS and video editing with a dedicated NVIDIA GPU.", False),
    ("zbook", "HP ZBook", "HP's mobile workstation line for engineers, architects and creators, with dedicated NVIDIA graphics and certified professional drivers.", False),
    ("omen", "HP Omen", "HP's premium gaming line, with high-refresh displays, strong cooling and NVIDIA GeForce RTX graphics.", False),
    ("victus", "HP Victus", "HP's mainstream gaming line: RTX graphics and a fast screen at a lower price than the Omen series.", False),
    ("spectre", "HP Spectre x360", "HP's premium consumer convertible, known for its gem-cut aluminium design, excellent screens and pen support.", True),
    ("omnibook", "HP OmniBook", "HP's newer consumer line for AI PCs, with efficient Intel Core Ultra processors and a built-in NPU for Windows AI features.", True),
    ("pavilion", "HP Pavilion", "HP's mainstream home laptop line, balancing price, design and everyday performance.", False),
    ("hp 250", "HP 250 series", "HP's value business notebook: a 15.6-inch workhorse for offices, schools and SMEs, popular in procurement because it is affordable and easy to service.", False),
    ("hp 15", "HP 15 series", "HP's everyday 15.6-inch home and student laptop with a full keyboard and number pad.", False),
    ("alienware", "Dell Alienware", "Dell's premium gaming brand, known for powerful cooling, high-refresh displays and top-tier NVIDIA RTX graphics.", False),
    ("xps", "Dell XPS 13", "Dell's premium ultraportable with a near-borderless screen and a machined aluminium body. Memory is soldered to the board, so choose the RAM you need at purchase.", True),
    ("latitude e72", "Dell Latitude E7240/E7250", "Dell's 12.5-inch premium business ultraportable from the 2013–2015 era: compact, sturdy and still useful as a light, affordable document and browsing machine.", False),
    ("latitude", "Dell Latitude", "Dell's business laptop line. The 7000 series is the premium tier and the 5000 series the mainstream tier, both built for durability and easy servicing.", False),
    ("precision", "Dell Precision", "Dell's workstation line, built for engineering, design and analytics software with Xeon processors and professional graphics support.", False),
    ("optiplex", "Dell OptiPlex", "Dell's best-selling business desktop line, used by offices, banks, schools and cyber cafés worldwide because it is reliable, quiet and easy to maintain.", False),
    ("x1 carbon", "Lenovo ThinkPad X1 Carbon", "Lenovo's flagship 14-inch business ultrabook with a carbon-fibre lid and a weight of roughly 1.1–1.2 kg. It keeps the famous ThinkPad keyboard and red TrackPoint.", True),
    ("x1 yoga", "Lenovo ThinkPad X1 Yoga", "the convertible version of the X1 Carbon: a 14-inch premium ThinkPad with a 360-degree hinge, touchscreen and pen support.", True),
    ("thinkpad e14", "Lenovo ThinkPad E14", "Lenovo's small-business ThinkPad: it keeps the ThinkPad keyboard and durability at a lower price than the T series.", False),
    ("thinkpad t", "Lenovo ThinkPad T series", "Lenovo's mainstream corporate ThinkPad, the line most companies buy in bulk. It is known for an excellent keyboard, TrackPoint, durability testing and easy repairs. Models ending in 's' are the slimmer versions.", False),
    ("thinkpad x2", "Lenovo ThinkPad X200 series", "Lenovo's compact 12.5-inch business ultraportable. It is small enough to carry all day yet keeps a full ThinkPad keyboard.", False),
    ("yoga 260", "Lenovo ThinkPad Yoga 260", "a 12.5-inch convertible ThinkPad that folds into a tablet and supports a pen.", True),
    ("yoga 370", "Lenovo ThinkPad Yoga 370", "a 13.3-inch convertible ThinkPad with touchscreen and 360-degree hinge.", True),
    ("yoga 11e", "Lenovo Yoga 11e", "a rugged 11.6-inch education laptop designed for classrooms, with reinforced corners and a spill-resistant keyboard.", True),
    ("legion", "Lenovo Legion", "Lenovo's gaming line, well regarded for cooling, keyboards and sustained performance under load.", False),
    ("thinkbook", "Lenovo ThinkBook", "Lenovo's modern small-business line: aluminium design, fingerprint login and business features at a mid-range price.", False),
    ("ideapad flex", "Lenovo IdeaPad Flex 5", "Lenovo's convertible home laptop with a touchscreen and 360-degree hinge.", False),
    ("ideapad", "Lenovo IdeaPad", "Lenovo's everyday home and student line, offering good value for school, browsing and office work.", False),
    ("v14", "Lenovo V14", "Lenovo's value business laptop for SMEs, built for everyday office work at an affordable price.", False),
    ("thinkcentre", "Lenovo ThinkCentre", "Lenovo's business desktop line, known for reliability, tool-less servicing and small footprints.", False),
    ("expertbook b1", "ASUS ExpertBook B1", "ASUS's entry business laptop, built to military-grade durability standards with business security features.", False),
    ("expertbook b3", "ASUS ExpertBook B3 Flip", "ASUS's mid-range business convertible with touchscreen and pen support.", False),
    ("expertbook b5", "ASUS ExpertBook B5 Flip", "ASUS's premium 13.3-inch business convertible, light and durable.", True),
    ("expertbook b7", "ASUS ExpertBook B7 Flip", "ASUS's flagship business convertible with premium build and security features.", True),
    ("rog", "ASUS ROG", "ASUS's Republic of Gamers line: premium gaming laptops with fast screens and powerful cooling.", False),
    ("x543", "ASUS X543", "ASUS's everyday 15.6-inch home laptop.", False),
    ("elitedesk", "HP EliteDesk", "HP's premium business desktop line, built for reliability and security in corporate offices.", False),
    ("prodesk", "HP ProDesk", "HP's mainstream business desktop line for offices, schools and cyber cafés.", False),
    ("290 g4", "HP 290", "HP's value business tower desktop.", False),
    ("all in one", "HP All-in-One", "an all-in-one desktop: the computer is built into the monitor, so there is one cable and a clean desk.", False),
    ("z2 g4", "HP Z2 Mini", "HP's tiny workstation: professional performance in a box that fits behind a monitor.", False),
    ("z240", "HP Z240", "HP's entry workstation, built to run continuously with professional reliability.", False),
    ("z440", "HP Z440", "HP's single-socket tower workstation with Xeon processors, lots of RAM slots and room for professional graphics cards.", False),
    ("z820", "HP Z820", "HP's high-end dual-processor tower workstation with many cores, ideal for rendering and heavy computation on a budget.", False),
    ("proliant", "HP ProLiant ML310e", "HP's entry tower server for small offices: file sharing, accounting databases, backups and small business applications.", False),
]

GPU_TIER = {
    "2060": "an older-generation RTX card that still handles most games at 1080p on medium-to-high settings",
    "3060": "a strong 1080p card that also handles many games at 1440p, with DLSS support for higher frame rates",
    "3070": "a high-end card for 1440p gaming and demanding 3D work",
    "4060": "a modern, efficient card for high-setting 1080p gaming with DLSS 3 frame generation",
    "4070": "a high-end card for 1440p gaming, streaming and GPU rendering",
    "5060": "a current-generation RTX 50-series card with DLSS 4 for high-setting 1080p and good 1440p gaming",
    "5070": "a current-generation RTX 50-series card for high-setting 1440p gaming and serious creative work",
}


def cpu_info(cpu, name):
    """Return dict: tier, gen, model, suffix, segment."""
    c = (cpu or "").lower()
    n = name.lower()
    info = {"tier": None, "gen": None, "model": None, "suffix": "", "segment": "U"}
    if "ultra" in c:
        info.update(tier="ultra")
    elif "xeon" in c:
        info.update(tier="xeon")
    elif "celeron" in c:
        info.update(tier="celeron")
    else:
        m = re.search(r"i([3579])", c)
        if m:
            info["tier"] = "i" + m.group(1)
    m = re.search(r"-(\d{4,5})([a-z]{0,2}\d?)", c)
    if m:
        num, suf = m.group(1), m.group(2).upper()
        info["model"] = num + suf
        info["gen"] = int(num[:2]) if len(num) == 5 else int(num[0])
        info["suffix"] = suf
    g = re.search(r"\((\d{1,2})(?:st|nd|rd|th) gen\)", c)
    if g:
        info["gen"] = int(g.group(1))
    if info["suffix"] in ("H", "HX") or any(k in n for k in ["omen", "legion", "victus", "rog", "alienware", "zbook power"]):
        info["segment"] = "H"
    if info["suffix"] in ("", "T") and info["model"]:
        info["segment"] = "D"
    return info


def cores_for(info, is_desktop):
    gen, tier = info["gen"], info["tier"]
    seg = "D" if is_desktop else info["segment"]
    if gen is None or tier is None:
        return None
    key_gen = "old" if gen <= 7 else gen
    return CORES.get((key_gen, tier, seg)) or CORES.get((key_gen, tier, "U" if seg != "D" else "D"))


def line_for(name):
    n = name.lower()
    for key, title, text, soldered in LINES:
        if key in n:
            return {"title": title, "text": text, "soldered": soldered}
    return None


def ram_gen_for(info, name):
    """Best-effort memory generation for upgrade advice."""
    n = name.lower()
    if "ddr5" in n:
        return "DDR5"
    gen = info.get("gen")
    if info.get("tier") == "ultra":
        return "on-package LPDDR5X (not upgradable)"
    if gen is None:
        if "xeon" in (info.get("tier") or "") and any(k in n for k in ["z820", "proliant", "ddr3"]):
            return "DDR3"
        return None
    if gen <= 3:
        return "DDR3"
    if gen <= 5:
        return "DDR3L" if not any(k in n for k in ["optiplex", "prodesk", "elitedesk", "thinkcentre", "desktop"]) else "DDR3"
    if gen <= 11:
        return "DDR4"
    return "DDR4 or DDR5 (depends on the exact model)"


def score(info, specs, name):
    """0–10 performance score used to decide the use-case table."""
    s = 0
    tier = info.get("tier")
    s += {"celeron": 0, "i3": 1, "i5": 2, "i7": 3, "i9": 4, "ultra": 3, "xeon": 3}.get(tier, 1)
    gen = info.get("gen") or (8 if tier == "xeon" else 5)
    s += 0 if gen <= 4 else 1 if gen <= 7 else 2 if gen <= 10 else 3
    ram = int(re.sub(r"\D", "", specs.get("ram", "0")) or 0)
    s += 0 if ram <= 4 else 1 if ram <= 8 else 2
    if "SSD" in specs.get("storage", "") or "ssd" in name.lower():
        s += 1
    if specs.get("gpu"):
        s += 2
    return min(s, 10)


TASKS = [
    ("Microsoft Office, email and browsing", 1),
    ("Zoom, Teams and Google Meet calls", 2),
    ("University research and online classes", 2),
    ("Accounting software (QuickBooks, Sage, Tally)", 3),
    ("Programming and web development", 4),
    ("Photo editing (Photoshop, Lightroom)", 5),
    ("AutoCAD 2D drafting", 5),
    ("Video editing (Premiere Pro, DaVinci Resolve)", 7),
    ("3D design and rendering (Revit, SketchUp, Blender)", 8),
    ("Modern AAA gaming", 8),
]


def task_verdict(sc, need, has_gpu):
    if need >= 7 and not has_gpu:
        return "Not recommended" if sc < 8 else "Light projects only"
    if sc >= need + 2:
        return "Excellent"
    if sc >= need:
        return "Good"
    if sc >= need - 1:
        return "Possible, with patience"
    return "Not recommended"
