"""Build a tiny search engine from a small slice of Common Crawl.

Streams one WET file (extracted page text) from Common Crawl's public data, keeps the first
1,000 suitable English pages, and stores them in an SQLite full-text index (FTS5).
Only Python's standard library is used. Nothing is downloaded beyond what is needed:
the stream is closed as soon as 1,000 pages are indexed.

usage: python3 build_index.py [CRAWL_ID] [PAGES]
"""
import gzip
import os
import re
import sqlite3
import sys
import time
import urllib.request
from urllib.parse import urlsplit

CRAWL = sys.argv[1] if len(sys.argv) > 1 else "CC-MAIN-2026-47"   # November 2026
PAGES = int(sys.argv[2]) if len(sys.argv) > 2 else 1000
KEEP = 5000                     # characters of text kept per page
DB = "search.db"
BASE = "https://data.commoncrawl.org/"
UA = {"User-Agent": "ScraperFinderDocBot/1.0 (https://scraperfinder.com; hello@scraperfinder.com)"}


class Metered:
    """Wraps the HTTP response and counts the compressed bytes we actually download."""
    def __init__(self, resp):
        self.resp, self.bytes = resp, 0

    def read(self, n=-1):
        data = self.resp.read(n)
        self.bytes += len(data)
        return data


def fetch(path):
    return urllib.request.urlopen(urllib.request.Request(BASE + path, headers=UA), timeout=60)


def records(stream):
    """Yield (headers, text) for each WARC record in a WET stream."""
    while True:
        line = stream.readline()
        if not line:
            return
        if not line.startswith(b"WARC/"):
            continue
        headers = {}
        while (line := stream.readline()) not in (b"\r\n", b"\n", b""):
            key, _, value = line.decode("utf-8", "replace").partition(":")
            headers[key.strip()] = value.strip()
        body = stream.read(int(headers.get("Content-Length", 0)))
        yield headers, body.decode("utf-8", "replace")


def same_page(url):
    """http://www.example.com/a/ and https://example.com/a are the same page to a reader."""
    u = urlsplit(url)
    host = u.netloc.lower().removeprefix("www.")
    return host + (u.path.rstrip("/") or "/") + ("?" + u.query if u.query else "")


def main():
    # 1. the list of WET files in this crawl (a small text file)
    with fetch(f"crawl-data/{CRAWL}/wet.paths.gz") as r:
        wet_files = gzip.decompress(r.read()).decode().split()
    wet = wet_files[0]
    print(f"{CRAWL}: {len(wet_files):,} WET files. Streaming the first one:")
    print(f"  {wet}")

    if os.path.exists(DB):
        os.remove(DB)
    db = sqlite3.connect(DB)
    db.execute("CREATE VIRTUAL TABLE pages USING fts5(url UNINDEXED, captured UNINDEXED, text)")

    seen, start = set(), time.time()
    skipped = {"duplicate URLs": 0, "not English": 0, "too little text": 0, "adult": 0}
    resp = fetch(wet)
    size = int(resp.headers.get("Content-Length", 0))
    raw = Metered(resp)
    for headers, text in records(gzip.GzipFile(fileobj=raw)):      # 2. read it progressively
        if headers.get("WARC-Type") != "conversion":
            continue                                                 # file header, not a page
        url = headers["WARC-Target-URI"]
        reason = None
        if same_page(url) in seen:
            reason = "duplicate URLs"
        elif not headers.get("WARC-Identified-Content-Language", "").startswith("eng"):
            reason = "not English"
        elif len(text) < 500:
            reason = "too little text"
        elif ADULT.search(url) or len(ADULT.findall(text)) >= 2:
            reason = "adult"
        if reason:
            skipped[reason] += 1
            continue
        seen.add(same_page(url))
        db.execute("INSERT INTO pages VALUES (?, ?, ?)",            # 3. index it
                   (url, headers["WARC-Date"][:10], text[:KEEP]))
        if len(seen) % 100 == 0:
            print(f"  {len(seen):>5,} pages indexed   {raw.bytes / 1e6:6.1f} MB downloaded")
        if len(seen) >= PAGES:
            break                                                    # 4. stop when we have enough
    resp.close()
    db.commit()
    db.execute("VACUUM")
    db.close()

    took = time.time() - start
    print(f"\nDone in {took:.1f} s")
    print(f"  pages indexed : {len(seen):,}")
    print(f"  skipped       : " + ", ".join(f"{n:,} {why}" for why, n in skipped.items()))
    print(f"  downloaded    : {raw.bytes / 1e6:.1f} MB of a {size / 1e6:.1f} MB WET file"
          f" ({raw.bytes / size:.0%})")
    print(f"  database      : {DB}  {os.path.getsize(DB) / 1e6:.1f} MB")


# Adult-content filter (kept at the end of the file so the list stays out of the way).
ADULT = re.compile(r"porn|xxx|nsfw|hentai|milf|onlyfans|camgirl|\bfuck|\bsex ?(video|tube|cam|chat)", re.I)


if __name__ == "__main__":
    main()
