"""Shared HTML helpers and sections used by every product writer."""
import hashlib
import html
import re

CAT_NAMES = {}  # filled by engine.build_context


def pick(seed, options):
    """Deterministic choice so the same product always gets the same wording, while different products vary."""
    h = int(hashlib.md5(seed.encode()).hexdigest(), 16)
    return options[h % len(options)]


def money(n):
    return f"KES {int(n):,}" if n else ""


def esc(s):
    return html.escape(str(s), quote=False)


def h2(t):
    return f"<h2>{t}</h2>"


def h3(t):
    return f"<h3>{t}</h3>"


def p(t):
    return f"<p>{t}</p>"


def ul(items):
    return "<ul>" + "".join(f"<li>{i}</li>" for i in items) + "</ul>"


def ol(items):
    return "<ol>" + "".join(f"<li>{i}</li>" for i in items) + "</ol>"


def table(head, rows):
    th = "".join(f"<th>{h}</th>" for h in head)
    body = "".join("<tr>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>" for r in rows)
    return f"<table><thead><tr>{th}</tr></thead><tbody>{body}</tbody></table>"


def faq(q, a):
    return {"q": q, "a": a}


def link_cat(slug, text=None):
    return f'<a href="/category/{slug}">{text or CAT_NAMES.get(slug, slug)}</a>'


def link_prod(p_):
    return f'<a href="/product/{p_["slug"]}">{p_["name"]}</a>'


def words(html_text):
    return len(re.sub(r"<[^>]+>", " ", html_text).split())


def similar_products(prod, ctx, n=3, same_type=None):
    """Closest-priced products in the same category (optionally same sub-type)."""
    pool = [x for x in ctx["by_cat"].get(prod["category"], []) if x["slug"] != prod["slug"]]
    if same_type:
        typed = [x for x in pool if same_type(x)]
        if len(typed) >= 2:
            pool = typed
    pool.sort(key=lambda x: (abs(x["price"] - prod["price"]), x["slug"]))
    return pool[:n]


def cheapest_in(ctx, cat, must=(), kind_word=None):
    pool = ctx["by_cat"].get(cat, [])
    for m in must:
        pool = [x for x in pool if m.lower() in x["name"].lower()]
    if kind_word:
        typed = [x for x in pool if kind_word.lower() in x["name"].lower()]
        pool = typed or pool
    return min((x["price"] for x in pool), default=None)


def price_position(prod, ctx, same_type=None):
    pool = ctx["by_cat"].get(prod["category"], [])
    if same_type:
        t = [x for x in pool if same_type(x)]
        pool = t if len(t) >= 3 else pool
    prices = sorted(x["price"] for x in pool)
    if len(prices) < 3:
        return ""
    rank = prices.index(prod["price"]) / (len(prices) - 1)
    lo, hi = money(prices[0]), money(prices[-1])
    where = ("one of the most affordable options" if rank < 0.25 else
             "a mid-range option" if rank < 0.7 else "one of the premium options")
    return (f"In our {CAT_NAMES.get(prod['category'], 'product')} range, where prices run from {lo} to {hi}, "
            f"this is {where}.")


def closing_sections(prod, ctx):
    """Price, delivery, payment, warranty and ordering: the same facts every buyer asks, written for this product."""
    name, price, w = prod["name"], prod["price"], prod["warranty_months"]
    free = price >= ctx["free_over"]
    out = [h2(f"{name}: price, delivery and warranty in Kenya")]
    out.append(p(f"The {name} is {money(price)} at {ctx['site']}"
                 + (f", down from {money(prod['compare_at'])}" if prod.get("compare_at") else "")
                 + ". " + price_position(prod, ctx)))
    out.append(table(["Option", "Details"], [
        ("Pickup", f"Free from our shop in {ctx['landmark']}, same day after payment"),
        ("Nairobi delivery", "Free on this item" if free else f"{money(ctx['fee_nbi'])}, same day if paid before 3pm, otherwise next day"),
        ("Countrywide courier", "Free on this item" if free else f"{money(ctx['fee_ctry'])}, 1–3 working days to any town"),
        ("Payment", "M-Pesa STK push at checkout, cash or M-Pesa in-store, bank transfer for companies"),
        ("Warranty", f"{w} months against hardware faults" if w else "Checked before dispatch; report any fault on arrival"),
        ("Returns", f"Faulty or not as described: report within {ctx['return_days']} days"),
    ]))
    out.append(h2("How to order"))
    out.append(ol([
        "Click <strong>Add to cart</strong> or <strong>Buy now with M-Pesa</strong>.",
        "Enter your name, Safaricom number and choose pickup or delivery.",
        "Approve the M-Pesa prompt on your phone with your PIN.",
        "You get an SMS confirmation and we call to arrange collection or delivery.",
    ]))
    out.append(p("Buying for a company, school or NGO? We provide official quotations, KRA-compliant invoices and "
                 "bulk pricing. Message us on WhatsApp with the quantity you need."))
    return out


def ORDER_FAQS(prod, ctx):
    w = prod["warranty_months"]
    return [
        faq(f"Do you deliver the {prod['name']} outside Nairobi?",
            "Yes. We deliver countrywide by courier in 1–3 working days, and same or next day within Nairobi. "
            "You can also pick it up free from our shop."),
        faq("What warranty does it come with?",
            (f"It comes with a {w}-month warranty against hardware faults. Physical and liquid damage are not covered."
             if w else "Consumables are checked before dispatch. Report any fault on arrival and we will replace it.")),
    ]
