"""Builds Seryva's local adult-domain database from licence-cleared sources (docs/legal/DOMAIN_LIST_LICENCES.md).

Inputs (downloaded into sources/, never committed):
  sources/ut1/adult/domains          UT1 adult category, CC BY-SA 4.0
  sources/ipfire-porn-domains.txt    IPFire DBL porn list, CC BY-SA 4.0
  sources/majestic_million.csv       Majestic Million, CC BY 3.0 (test data only, never shipped)

Outputs (output/):
  adult_domains.txt      the shipped list as plain text, CC BY-SA 4.0 (share-alike, published with the app notices)
  adult_domains.bin      the same list as sorted 64-bit FNV-1a hashes for the app (see CompactDomainSet.kt)
  review_top_sites.txt   listed domains that would block a Majestic top-100k site without corroboration (held back)
  stats.json             counts, source hashes, cross-source agreement and false-block measurements

Matching rule (same as the app): a host is blocked when the host or any parent of it with at least two labels is in
the list. So entries are kept at full host level (no collapsing to the registrable domain, which would block whole
parents such as blogspot.com), and an entry whose parent is already listed is redundant and dropped.

Run:  python -I build_domain_db.py
"""
import encodings.idna  # noqa: F401  (registers the idna codec)
import hashlib
import json
import re
import struct
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
SRC = ROOT / "sources"
OUT = ROOT / "output"
LABEL = re.compile(r"^(?!-)[a-z0-9-]{1,63}(?<!-)$")
TLD = re.compile(r"^(?:[a-z]{2,24}|xn--[a-z0-9-]{1,59})$")
STRIP_PREFIXES = ("www.", "m.", "mobile.")
INSTITUTIONAL = re.compile(r"(?:^|\.)(?:gov|edu|mil|int|gouv|gob|govt)(?:\.[a-z]{2})?$|(?:^|\.)(?:ac|sch)\.[a-z]{2}$")
MAGIC = b"SRVADB01"
HELD_OUT_OFFSET = 17

# Names that make an adult listing of a popular site credible on their own. "sex" is left out on purpose: it is
# inside sussex.ac.uk, essex.gov.uk and middlesex.edu.
ADULT_TOKENS = (
    "porn", "xxx", "hentai", "xvideo", "xnxx", "xhamster", "nsfw", "milf", "fuck", "nude", "naked", "onlyfans",
    "camgirl", "erotic", "escort", "fetish", "bdsm", "redtube", "youporn", "chaturbate", "stripchat", "bongacams",
    "livejasmin", "spankbang", "brazzers", "javhd", "rule34", "booru", "lewd",
)


def normalize(raw):
    host = raw.strip().lower().rstrip(".")
    if not host or host.startswith("#") or "/" in host or ":" in host or " " in host:
        return None
    for prefix in STRIP_PREFIXES:
        if host.startswith(prefix) and host.count(".") >= 2:
            host = host[len(prefix):]
    if not host.isascii():
        try:
            host = host.encode("idna").decode("ascii")
        except UnicodeError:
            return None
    labels = host.split(".")
    if len(labels) < 2 or len(host) > 253 or not all(LABEL.match(l) for l in labels) or not TLD.match(labels[-1]):
        return None
    return host


def parents(host):
    labels = host.split(".")
    return [".".join(labels[i:]) for i in range(1, len(labels) - 1)]


def suffixes(host):
    labels = host.split(".")
    return [".".join(labels[i:]) for i in range(0, len(labels) - 1)]


def fnv1a64(text):
    h = 0xCBF29CE484222325
    for b in text.encode("ascii"):
        h ^= b
        h = (h * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF
    return h - (1 << 64) if h >= (1 << 63) else h  # signed, as Kotlin Long


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def load(path, skip_comments=True):
    out, bad = set(), 0
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            if skip_comments and line.startswith("#"):
                continue
            host = normalize(line)
            if host:
                out.add(host)
            elif line.strip():
                bad += 1
    return out, bad


def minimal(hosts):
    """Drops hosts whose listed parent already covers them."""
    return {h for h in hosts if not any(p in hosts for p in parents(h))}


def blocked_by(host, listed):
    return next((s for s in suffixes(host) if s in listed), None)


def curated():
    """The hand-checked domains already in DomainRiskEngine.DEFAULT_BLOCKED_DOMAINS."""
    kt = (ROOT.parent / "app/src/main/java/com/blockero/app/accessibility/DomainRiskEngine.kt").read_text(encoding="utf-8")
    block = kt[kt.index("DEFAULT_BLOCKED_DOMAINS"):]
    block = block[:block.index(")")]
    return {h for h in (normalize(x) for x in re.findall(r'"([^"]+)"', block)) if h}


# More adult name words, measured on held-out samples 2026-12-03. "sex" skips essex, sussex, middlesex, wessex,
# unisex, sexton, sextant, sextet and sextile.
EXTRA_ADULT = re.compile(
    r"(?<!es)(?<!ss)(?<!le)(?<!uni)(?<!wes)sex(?!t(?:on|ant|et|ile))|slut|whore|dildo|kink|orgy|hardcore|hooker|stripper")
# Names that only look adult: the "X porn" photo genres, sexual health and education, sex-worker rights groups.
BENIGN_NAME = re.compile(
    r"(?:food|book|bookshelf|earth|cabin|ruin|space|map|gear|design|architecture|car|city|sky|cable|tech|art|kitchen)porn"
    r"|sexpistol|sexolog|sexualit|sexualhealth|sexhealth|sexeducat|sexwork|sexualassault|sextortion")


def adult_name(host):
    if BENIGN_NAME.search(host):
        return False
    return any(t in host for t in ADULT_TOKENS) or bool(EXTRA_ADULT.search(host))


def main():
    ut1, ut1_bad = load(SRC / "ut1" / "adult" / "domains")
    ipfire, ipfire_bad = load(SRC / "ipfire-porn-domains.txt")
    hand = curated()
    ut1_min, ipfire_min = minimal(ut1), minimal(ipfire)
    in_both = ut1 & ipfire
    # UT1's adult category is noisy (it lists vk.com, menshealth.com, lingerie shops and LGBT organisations), so a
    # UT1-only entry ships only when its own name is clearly adult. IPFire's curated porn sources ship whole.
    union = minimal(ipfire | in_both | {h for h in ut1 if adult_name(h)} | hand)
    # Institutional hosts are never blocked by a downloaded list (a hacked county site and a school were listed).
    union = {h for h in union if not INSTITUTIONAL.search(h)}

    majestic = []
    with open(SRC / "majestic_million.csv", encoding="utf-8", errors="replace") as f:
        next(f)
        for line in f:
            parts = line.split(",")
            host = normalize(parts[2]) if len(parts) > 2 else None
            if host:
                majestic.append(host)
    # Every 20th Majestic site (offset 17: never inspected while the rules were tuned on offsets 3, 7 and 13) is kept
    # out of the popular-site filter for the measurement below; it is filtered afterwards for the shipped list.
    held_out = majestic[HELD_OUT_OFFSET::20]
    filtered = [s for i, s in enumerate(majestic) if i % 20 != HELD_OUT_OFFSET]

    # Popular sites (Majestic top 1M): a listing that would block one ships only with corroboration: both sources,
    # an adult name, or the hand-checked list. Everything else is held back for review.
    review, kept_top = [], []
    for site in filtered:
        entry = blocked_by(site, union)
        if entry is None:
            continue
        if entry in in_both or site in in_both:
            why = "both-sources"
        elif entry in hand or site in hand:
            why = "hand-checked"
        elif adult_name(site):
            why = "adult-name"
        else:
            why = None
        (kept_top if why else review).append((site, entry, why or "single-source"))
    for _site, entry, _why in review:
        union.discard(entry)
    shipped = sorted(union)
    # Strong entries hard-block: a clearly adult name or the hand-checked list. Everything else, including entries
    # both sources list without an adult name (stale and hacked sites showed up there), is weak: a visual check only.
    strong = {h for h in shipped if h in hand or adult_name(h)}
    weak = [h for h in shipped if h not in strong]

    # Held-out popular sites (5% of Majestic, never used for filtering): every hit is listed for labelling; hits
    # without an adult name are the likely false blocks.
    held_hits = [(s, blocked_by(s, union)) for s in held_out]
    held_hits = [(s, e) for s, e in held_hits if e]
    held_no_name = [(s, e) for s, e in held_hits if not adult_name(s)]
    held_strong_no_name = [(s, e) for s, e in held_no_name if e in strong]
    held_strong_hits = [(s, e) for s, e in held_hits if e in strong]

    # The measurement is done: filter the held-out sites too, so the shipped list covers the whole top 1M.
    for site in held_out:
        entry = blocked_by(site, union)
        if entry and not (entry in hand or site in hand or adult_name(site) or entry in in_both or site in in_both):
            review.append((site, entry, "single-source"))
            union.discard(entry)
    shipped = sorted(union)
    strong = {h for h in shipped if h in hand or adult_name(h)}
    weak = [h for h in shipped if h not in strong]

    # Cross-source agreement: how much of each source the other one already blocks (an independent recall proxy).
    def coverage(target, listed):
        hit = sum(1 for h in target if blocked_by(h, listed))
        return round(hit / len(target), 4) if target else None

    OUT.mkdir(exist_ok=True)
    (OUT / "adult_domains.txt").write_text(
        "# Seryva adult domain list. CC BY-SA 4.0. Derived from: UT1 Blacklists (Universite Toulouse Capitole, "
        "CC BY-SA 4.0) and IPFire DBL porn list (CC BY-SA 4.0). Changes: normalised, deduplicated, subdomains of "
        "listed parents removed, uncorroborated listings of popular sites removed.\n" + "\n".join(shipped) + "\n",
        encoding="utf-8")
    def write_bin(name, hosts):
        hashes = sorted({fnv1a64(h) for h in hosts})
        with open(OUT / name, "wb") as f:
            f.write(MAGIC)
            f.write(struct.pack(">i", len(hashes)))
            f.write(struct.pack(f">{len(hashes)}q", *hashes))
        return len(hosts) - len(hashes)

    collisions = write_bin("adult_domains_strong.bin", strong) + write_bin("adult_domains_weak.bin", weak)
    (OUT / "adult_domains.bin").unlink(missing_ok=True)
    with open(OUT / "review_top_sites.txt", "w", encoding="utf-8") as f:
        f.write("# Majestic top-1M sites only one source lists as adult; held back from the shipped list for review\n")
        for site, entry, why in review:
            f.write(f"{site}\t{entry}\t{why}\n")
    with open(OUT / "held_out_strong_hits.txt", "w", encoding="utf-8") as f:
        f.write("# Held-out popular sites the STRONG level would hard-block; label each one: adult or mistake\n")
        for site, entry in held_strong_hits:
            f.write(f"{site}\t{entry}\n")
    with open(OUT / "held_out_hits_without_adult_name.txt", "w", encoding="utf-8") as f:
        for site, entry in held_no_name:
            f.write(f"{site}\t{entry}\t{'strong' if entry in strong else 'weak'}\n")

    stats = {
        "sources": {
            "ut1_adult": {"sha256": sha256(SRC / "ut1-adult.tar.gz"), "valid_hosts": len(ut1), "rejected_lines": ut1_bad,
                          "after_parent_dedup": len(ut1_min), "licence": "CC BY-SA 4.0"},
            "ipfire_porn": {"sha256": sha256(SRC / "ipfire-porn-domains.txt"), "valid_hosts": len(ipfire),
                            "rejected_lines": ipfire_bad, "after_parent_dedup": len(ipfire_min), "licence": "CC BY-SA 4.0"},
            "majestic_million_test_only": {"sha256": sha256(SRC / "majestic_million.csv"), "hosts": len(majestic),
                                           "licence": "CC BY 3.0", "shipped": False},
        },
        "shipped_entries": len(shipped),
        "strong_entries": len(strong),
        "weak_entries": len(weak),
        "hash_collisions": collisions,
        "strong_bin_bytes": (OUT / "adult_domains_strong.bin").stat().st_size,
        "weak_bin_bytes": (OUT / "adult_domains_weak.bin").stat().st_size,
        "majestic_filtered_sites": len(filtered),
        "popular_blocked_kept_corroborated": len(kept_top),
        "popular_held_back_for_review": len(review),
        "held_out_sites": len(held_out),
        "held_out_hits": len(held_hits),
        "held_out_hits_without_adult_name": len(held_no_name),
        "held_out_upper_bound_false_block_rate": round(len(held_no_name) / len(held_out), 5),
        "held_out_offset": HELD_OUT_OFFSET,
        "held_out_strong_hits": len(held_strong_hits),
        "held_out_strong_hits_without_adult_name": len(held_strong_no_name),
        "held_out_strong_upper_bound_false_block_rate": round(len(held_strong_no_name) / len(held_out), 5),
        "cross_source_recall": {
            "ut1_blocks_share_of_ipfire": coverage(ipfire_min, ut1_min),
            "ipfire_blocks_share_of_ut1": coverage(ut1_min, ipfire_min),
        },
    }
    (OUT / "stats.json").write_text(json.dumps(stats, indent=1), encoding="utf-8")
    print(json.dumps(stats, indent=1))


if __name__ == "__main__":
    sys.exit(main())
