"""Long-form SEO/AEO content for every non-computer product, driven by the product-type knowledge base."""
import re

from .common import (pick, money, link_cat, link_prod, closing_sections, faq, h2, h3, p, ul, ol, table,
                     similar_products, price_position, ORDER_FAQS)
from .kb_types_a import TYPES_A
from .kb_types_b import TYPES_B
from .kb_types_c import TYPES_C, FALLBACK
from .kb_extra import TROUBLE, TYPE_GROUP, BUNDLES
from .kb_more import MORE
from .variants import variant_sections

TYPES = TYPES_A + TYPES_B + TYPES_C

BRAND_NOTES = {
    "HP": "HP is one of the world's largest computer and printer makers, with wide parts and service availability in Kenya.",
    "Dell": "Dell is a leading business computer brand known for reliable, serviceable hardware.",
    "Lenovo": "Lenovo is the world's largest PC maker by volume and the company behind the ThinkPad range.",
    "Canon": "Canon is a leading Japanese imaging brand known for dependable printers and cameras.",
    "Epson": "Epson pioneered ink tank printing with its EcoTank range and is a leader in projectors and dot matrix printers.",
    "Logitech": "Logitech is a leading Swiss brand for webcams, presenters, mice and keyboards.",
    "ZKTeco": "ZKTeco is one of the most widely used biometric and access control brands in Kenya, with strong local support.",
    "SecuGen": "SecuGen is a US biometrics company whose Hamster scanners are widely used for identity verification.",
    "Xprinter": "Xprinter is a popular POS printer brand offering reliable receipt and label printers at good prices.",
    "Honeywell": "Honeywell is a global leader in barcode scanning used by major retailers and warehouses.",
    "Xiaomi": "Xiaomi is a major global electronics brand known for value-packed smart devices.",
    "Anker": "Anker is a leading charging brand known for safe, reliable power banks and chargers.",
    "Apple": "Apple's genuine chargers are designed for safe, efficient charging of iPhone, iPad and MacBook devices.",
    "Mercury": "Mercury is a popular UPS brand in Kenya offering dependable backup power for homes and offices.",
    "Evolis": "Evolis is a French specialist in plastic card printers used by schools, companies and banks.",
    "DYMO": "DYMO is a long-established label maker brand for offices and industry.",
    "Bose": "Bose is an American audio brand known for sound quality.",
}


def find_type(prod):
    n = " " + prod["name"].lower() + " "
    for t in TYPES:
        if prod["category"] in t["cats"] and t["match"](n):
            return t
    for t in TYPES:
        if t["match"](n):
            return t
    return FALLBACK


def attrs(prod, t):
    """Product-specific attributes pulled from the name for the facts table."""
    n = prod["name"]
    a = []
    m = re.search(r"(\d+)\s*(GB|TB)", n, re.I)
    if t["key"] in ("ram", "nvme", "m2sata", "msata", "sata25", "hdd") and m:
        a.append(("Capacity", m.group(1) + m.group(2).upper()))
    if t["key"] == "ram":
        g = re.search(r"DDR\d", n, re.I)
        a.append(("Type", g.group(0).upper() if g else ("DDR4" if "3200" in n or "2666" in n or "2400" in n else "DDR3")))
        s = re.search(r"(\d{4})\s*/?\s*\d*\s*MHz|(\d{4})MHz", n, re.I) or re.search(r"(\d{4})", n)
        if s:
            a.append(("Speed", f"{next(x for x in s.groups() if x)} MHz"))
        a.append(("Form factor", "SODIMM (laptop)" if "laptop" in n.lower() else "DIMM (desktop)" if "desktop" in n.lower() else "Check listing"))
    if t["key"] in ("nvme", "m2sata"):
        f = re.search(r"(2280|2242|2230)", n)
        a.append(("Length", f"M.2 {f.group(1)}" if f else "M.2 2280"))
        a.append(("Interface", "PCIe NVMe" if t["key"] == "nvme" else "SATA (M.2)"))
    if t["key"] == "hdd":
        a.append(("Size", "2.5\" laptop" if "laptop" in n.lower() or "slim" in n.lower() else "3.5\" desktop"))
    m = re.search(r"(\d+(?:\.\d)?)\s*M\b", n)
    if t["key"] == "video_cable" and m:
        a.append(("Length", m.group(1) + " m"))
    m = re.search(r"(\d{3,4})\s*va", n, re.I)
    if m:
        a.append(("Capacity", m.group(1) + "VA"))
    m = re.search(r"(\d)\s*way", n, re.I)
    if m:
        a.append(("Sockets", m.group(1)))
    m = re.search(r"(\d+)\s*(?:mm)?\s*[x×]\s*(\d+)\s*mm", n, re.I)
    if m and t["key"] == "labels":
        a.append(("Label size", f"{m.group(1)} × {m.group(2)} mm"))
    m = re.search(r"(\d{2})\s*(?:″|\"|inch|-inch| inches)", n, re.I)
    if m and t["key"] in ("monitor", "pos_terminal", "pos_screen"):
        a.append(("Screen size", m.group(1) + "\""))
    m = re.search(r"(\d{4,5})\s*mah", n, re.I)
    if m:
        a.append(("Battery", m.group(1) + " mAh"))
    m = re.search(r"(\d+)\s*w\b", n, re.I)
    if m and t["key"] in ("speaker", "charger", "power_adapter"):
        a.append(("Power", m.group(1) + "W"))
    m = re.search(r"(\d+)\s*in\s*1", n, re.I)
    if m:
        a.append(("Ports", f"{m.group(1)}-in-1"))
    m = re.search(r"\b(80|76|58|57)\s*mm\b", n, re.I)
    if m and t["key"] in ("receipt_printer", "dotmatrix", "thermal_roll", "pos_terminal"):
        a.append(("Paper width", m.group(1) + " mm"))
    low = n.lower()
    conn = [lab for kw, lab in (("usb", "USB"), ("lan", "LAN/Ethernet"), ("wi-fi", "Wi-Fi"), ("wifi", "Wi-Fi"),
                                ("bluetooth", "Bluetooth"), ("blue-tooth", "Bluetooth"), ("4g", "4G"), ("5g", "5G"))
            if re.search(r"(?<![a-z])" + re.escape(kw) + r"(?![a-z])", low)]
    if "wireless" in low and not conn:
        conn.append("Wireless")
    if conn and t["key"] not in ("ram", "nvme", "m2sata", "msata", "sata25", "hdd"):
        a.append(("Connectivity", ", ".join(dict.fromkeys(conn))))
    return a


def ram_compat(prod, ctx):
    """List computers in the shop that this RAM module is likely to suit."""
    n = prod["name"].lower()
    is_laptop = "laptop" in n
    gen = "ddr3" if "ddr3" in n or "1333" in n or "1600" in n else "ddr4"
    cats = ["refurbished-laptops", "new-laptops"] if is_laptop else ["desktops"]
    hits = []
    for c in cats:
        for x in ctx["by_cat"].get(c, []):
            cpu = x["specs"].get("cpu", "")
            g = re.search(r"\((\d+)(?:st|nd|rd|th) Gen\)", cpu) or re.search(r"-(\d{4,5})", cpu)
            if not g:
                continue
            num = g.group(1)
            gn = int(num[:2]) if len(num) == 5 else int(num[0]) if len(num) == 4 else int(num)
            if (gen == "ddr3" and gn <= 4) or (gen == "ddr4" and 6 <= gn <= 11):
                hits.append(x)
    hits.sort(key=lambda x: x["price"])
    return hits[:4]


def write(prod, ctx):
    t = find_type(prod)
    name, price, w, cond = prod["name"], prod["price"], prod["warranty_months"], prod["condition"]
    brand = prod["brand"] if prod["brand"] != "Generic" else None
    label = t["label"]
    cat_link = link_cat(prod["category"])
    out = []

    # ---------- Intro ----------
    intro = (f"The <strong>{name}</strong> is {'a refurbished' if cond == 'refurbished' else 'a new'} {label} available at "
             f"{ctx['site']} for <strong>{money(price)}</strong>"
             + (f" with a {w}-month warranty" if w else "")
             + f". {first_sentence(t['what'])} ")
    intro += pick(name, [
        f"Below you'll find what it does, who it suits, how to choose and set it up, and how it compares with other options in our {cat_link} range.",
        f"This guide covers its key features, typical uses, compatibility, setup and care, so you can buy with confidence.",
        f"Read on for features, uses, a buying guide, setup steps and answers to common questions about this {label}.",
    ])
    out.append(p(intro))

    facts = [("Product type", label[0].upper() + label[1:]), ("Brand", prod["brand"]),
             ("Condition", "Refurbished" if cond == "refurbished" else "New"), ("Price", money(price))]
    facts += attrs(prod, t)
    facts.append(("Warranty", f"{w} months" if w else "Checked before dispatch"))
    facts.append(("Availability", "In stock: pickup or delivery" if prod.get("stock", 0) > 0 else "On order"))
    out.append(h2(f"{name}: key facts"))
    out.append(table(["Feature", "Details"], facts))

    # ---------- What is it ----------
    out.append(h2(f"What is {article(label)} {label}?"))
    out.append(p(t["what"]))
    if t["key"] in MORE:
        out.append(p(MORE[t["key"]]))
    if brand and brand in BRAND_NOTES:
        out.append(p(f"<strong>About {brand}:</strong> {BRAND_NOTES[brand]}"))
    elif brand:
        out.append(p(f"This unit is made by {brand}. We stock it because it offers dependable performance for the price, "
                     "and we support it locally from our Nairobi shop."))
    else:
        out.append(p(pick(name + "gen", [
            "This is a quality-checked generic-brand unit. We stock it because it delivers the core features most buyers need at a lower price than big-name equivalents, and we stand behind it with local support.",
            "It is a value-brand model: you get the essential features for the job without paying for a premium label, and we back it with our own after-sales support.",
            "As a generic-brand product, it keeps costs down while doing the job reliably. Every unit is checked before dispatch, and our team in Nairobi can help if you have any questions.",
        ])))

    # ---------- Variant-specific ----------
    out += variant_sections(prod, t, ctx)

    # ---------- Features ----------
    out.append(h2("Key features"))
    out.append(ul(t["features"] + product_feature_lines(prod, t)))

    # ---------- Uses ----------
    out.append(h2(f"Who is the {short(name)} for?"))
    out.append(p(pick(name + "uses", [
        f"Customers buy this {label} for many jobs. The most common are:",
        f"Here are the typical ways our customers use this {label}:",
        f"This {label} is a good fit for:",
    ])))
    out.append(ul(t["uses"]))

    # ---------- Choosing ----------
    out.append(h2(f"How to choose the right {label}"))
    out.append(ul(t["choose"]))
    out.append(p(why_this_one(prod, t, ctx)))

    # ---------- Compatibility ----------
    out.append(h2("Compatibility"))
    out.append(p(t["compat"]))
    if t["key"] == "ram":
        comp = ram_compat(prod, ctx)
        if comp:
            out.append(p("Computers in our shop that typically use this type of memory include:"))
            out.append(ul([link_prod(x) + f" ({money(x['price'])})" for x in comp]))
            out.append(p("Always confirm the exact memory type of your own machine before buying; we're happy to check it for you."))

    # ---------- Setup ----------
    out.append(h2(f"How to set up the {short(name)}"))
    out.append(ol(t["setup"]))

    # ---------- Care ----------
    out.append(h2("Care and maintenance tips"))
    out.append(ul(t["care"] + ["Keep your receipt: it is your warranty proof." if w else "Inspect on arrival and report any issue immediately."]))

    # ---------- Troubleshooting ----------
    trouble = TROUBLE.get(TYPE_GROUP.get(t["key"], "accessory"), TROUBLE["accessory"])
    out.append(h2("Common problems and quick fixes"))
    out.append(ul([f"<strong>{q}</strong>: {a}" for q, a in trouble]))
    out.append(p("Still stuck? Call or WhatsApp us. Most issues can be solved over the phone, and you can bring the "
                 "item to our shop for a free check during the warranty period."))

    # ---------- Bought together ----------
    addons = bundle_items(prod, t, ctx)
    if addons:
        out.append(h2("Frequently bought together"))
        out.append(p(f"Customers who buy {article(label)} {label} often add:"))
        out.append(ul([f"{link_prod(x)}: {money(x['price'])}" for x in addons]))

    # ---------- Alternatives ----------
    sims = similar_products(prod, ctx, n=4, same_type=lambda x: find_type(x)["key"] == t["key"])
    if sims:
        out.append(h2("Similar products and alternatives"))
        out.append(p(f"Comparing options? Here are other {plural(label)} and related items in our shop:"))
        out.append(table(["Product", "Price", "Condition"],
                         [(link_prod(s), money(s["price"]), "Refurbished" if s["condition"] == "refurbished" else "New")
                          for s in sims]))
        out.append(p(compare_line(prod, sims, label)))

    out.append(h2(f"Why buy from {ctx['site']}?"))
    out.append(ul([
        "Real shop in " + ctx["landmark"] + ": see and test before you pay",
        "Genuine stock, checked before dispatch" + (f", with a written {w}-month warranty" if w else ""),
        "Secure M-Pesa checkout with instant SMS confirmation",
        "Same/next-day Nairobi delivery and countrywide courier",
        "Official quotations and KRA invoices for companies, schools and NGOs",
        "Friendly technical advice before and after you buy",
    ]))

    out += closing_sections(prod, ctx)

    faqs = [faq(f"How much is the {short(name)} in Kenya?",
                f"The {name} costs {money(price)} at {ctx['site']}. Pay with M-Pesa online, or visit our shop in {ctx['landmark']}.")]
    faqs += [faq(q, a) for q, a in t["faqs"]]
    faqs += ORDER_FAQS(prod, ctx)
    return {"html": "".join(out), "faqs": faqs}


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

def first_sentence(text):
    return text.split(". ")[0].rstrip(".") + "."


VOWEL_SOUND_ACRONYMS = ("EAS", "HDMI", "M.2", "NVMe", "mSATA", "SSD", "ID ", "MSR", "LED", "SATA")


def article(word):
    if word.startswith(VOWEL_SOUND_ACRONYMS[:-1]):
        return "an"
    if word.startswith(("RAM", "UPS", "USB", "uni", "SATA")):
        return "a"
    return "an" if word[:1].lower() in "aeiou" else "a"


def plural(label):
    if label.endswith("y") and not label.endswith("ey"):
        return label[:-1] + "ies"
    if label.endswith(("s", "x", "ch")):
        return label + "es"
    if " or " in label or label.endswith("component"):
        return label + "s"
    return label + "s"


def short(name):
    base = re.sub(r"\s*\([^)]*\)", "", name)
    s = re.split(r",| – | with | for |\|", base)[0].strip()
    if len(s.split()) < 3 and base != s:
        s = base.split(",")[0].strip()
    return s if 6 <= len(s) <= 70 else name[:60]


def product_feature_lines(prod, t):
    lines = []
    n = prod["name"].lower()
    if "wireless" in n and t["key"] not in ("earphones", "speaker"):
        lines.append("Wireless operation for flexible placement")
    if "refurbished" in n or prod["condition"] == "refurbished":
        lines.append("Refurbished and tested by our technicians before sale")
    if prod["warranty_months"] >= 12:
        lines.append(f"{prod['warranty_months']}-month warranty for peace of mind")
    if "original" in n:
        lines.append("Original part, not a copy")
    return lines


def why_this_one(prod, t, ctx):
    pos = price_position(prod, ctx, same_type=lambda x: find_type(x)["key"] == t["key"])
    bits = [pos] if pos else []
    if prod.get("compare_at"):
        bits.append(f"It is currently {money(prod['compare_at'] - prod['price'])} below its listed price.")
    bits.append(pick(prod["slug"], [
        "If you're unsure whether it's the right fit, send us a WhatsApp message with your setup and we'll advise.",
        "Not sure? Our team will gladly confirm it suits your equipment before you pay.",
        "Need help deciding? Call or WhatsApp us and we'll recommend the best option for your use and budget.",
    ]))
    return " ".join(bits)


def compare_line(prod, sims, label):
    cheaper = [s for s in sims if s["price"] < prod["price"]]
    pricier = [s for s in sims if s["price"] > prod["price"]]
    parts = []
    if cheaper:
        parts.append(f"For a tighter budget, the {cheaper[0]['name']} is {money(prod['price'] - cheaper[0]['price'])} less.")
    if pricier:
        parts.append(f"If you need more, the {pricier[0]['name']} costs {money(pricier[0]['price'] - prod['price'])} more.")
    if not parts:
        parts.append("These alternatives are similarly priced; compare features to pick the best fit.")
    return " ".join(parts)


def bundle_items(prod, t, ctx, n=3):
    picks, seen = [], {prod["slug"]}
    for cat, kw in BUNDLES.get(t["key"], []):
        pool = [x for x in ctx["by_cat"].get(cat, []) if kw in x["name"].lower() and x["slug"] not in seen]
        if not pool:
            continue
        pool.sort(key=lambda x: (x["price"], x["slug"]))
        choice = pool[len(pool) // 3]  # a sensible mid-low priced pick rather than the cheapest every time
        picks.append(choice)
        seen.add(choice["slug"])
        if len(picks) >= n:
            break
    return picks
