"""Generates long-form SEO/AEO content for every product in the catalogue."""
import re
from collections import defaultdict

from . import common
from .common import words

COMPUTER_CATS = {"refurbished-laptops", "new-laptops", "gaming-laptops", "desktops"}
MIN_WORDS = 700


def build_context(products, categories, site, landmark="Nairobi CBD", fee_nbi=300, fee_ctry=600, free_over=50000,
                  return_days=7):
    by_cat = defaultdict(list)
    for p_ in products:
        by_cat[p_["category"]].append(p_)
    common.CAT_NAMES.update({c["slug"]: c["name"] for c in categories})
    return {"site": site, "landmark": landmark, "fee_nbi": fee_nbi, "fee_ctry": fee_ctry, "free_over": free_over,
            "return_days": return_days, "by_cat": by_cat, "products": products}


def write_product(prod, ctx):
    if prod["category"] in COMPUTER_CATS:
        from .writer_computers import write
    else:
        from .writer_types import write
    res = write(prod, ctx)
    html, faqs = res["html"], res["faqs"]
    n = words(html)
    if n < MIN_WORDS:
        raise ValueError(f"{prod['name']}: only {n} words")
    return html, faqs, res.get("best_for")


def anchor_headings(html):
    """Give every <h2> an id so the product page can build an 'On this page' list (and Google jump links)."""
    used = set()

    def repl(m):
        text = re.sub(r"<[^>]+>", "", m.group(1))
        slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:50] or "section"
        base, i = slug, 2
        while slug in used:
            slug, i = f"{base}-{i}", i + 1
        used.add(slug)
        return f'<h2 id="{slug}">{m.group(1)}</h2>'
    return re.sub(r"<h2>(.*?)</h2>", repl, html)


def apply(products, categories, site, **kw):
    ctx = build_context(products, categories, site, **kw)
    stats = []
    for prod in products:
        html, faqs, best_for = write_product(prod, ctx)
        prod["description"] = anchor_headings(html)
        prod["faqs"] = faqs
        stats.append(words(html) + sum(words(f["q"] + " " + f["a"]) for f in faqs))
    return stats
