"""Fetch a small general text sample from Wikipedia for measuring dictionary coverage.

Usage: fetch-wikipedia-sample.py [--cache DIR] [--titles FILE] <language code> <output.txt> [<title>...]

Downloads the beginning of each article as plain text through the MediaWiki API, at most
MAX_BYTES_PER_ARTICLE of every response, so thirty articles stay under one megabyte. The response
is JSON with unescaped UTF-8 (`formatversion=2`), so the limit holds the same amount of text in
every script; until 2026-11-24 non-ASCII letters came as `\\uXXXX` and Greek or Cyrillic samples
held a third of the text. The sample is only measured, never bundled. Wikipedia text is licensed
CC BY-SA 4.0.

`--titles` reads one title per line. `--cache` keeps every response in DIR, so an interrupted run
continues where it stopped; HTTP 429 (too many requests) is waited out without a limit.
"""
import argparse
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

MAX_BYTES_PER_ARTICLE = 33_000
PAUSE_SECONDS = 3
FIRST_RETRY_SECONDS = 20
LONGEST_RETRY_SECONDS = 300
MARKER = '"extract":"'
USER_AGENT = "dictionary-coverage-sample/1.0 (generic script)"


def extract_text(raw):
    """Plain text from a possibly truncated API response."""
    body = raw.decode("utf-8", "ignore")
    start = body.find(MARKER)
    if start < 0:
        return ""
    text = body[start + len(MARKER):]
    end = 0
    while end < len(text) and text[end] != '"':
        end += 2 if text[end] == "\\" else 1
    text = text[:min(end, len(text))]
    # A response cut inside an escape sequence loses that sequence.
    while text:
        try:
            return json.loads(f'"{text}"')
        except json.JSONDecodeError:
            text = text[:-1]
    return ""


def fetch(language, title):
    query = urllib.parse.urlencode({
        "action": "query", "format": "json", "formatversion": 2, "prop": "extracts", "explaintext": 1,
        "exsectionformat": "plain", "redirects": 1, "titles": title,
    })
    request = urllib.request.Request(f"https://{language}.wikipedia.org/w/api.php?{query}",
                                     headers={"User-Agent": USER_AGENT})
    wait = FIRST_RETRY_SECONDS
    while True:
        try:
            with urllib.request.urlopen(request, timeout=60) as response:
                return response.read(MAX_BYTES_PER_ARTICLE)
        except urllib.error.HTTPError as error:
            if error.code != 429:
                raise
            print(f"  429 on {title}, waiting {wait} s", flush=True)
            time.sleep(wait)
            wait = min(wait * 2, LONGEST_RETRY_SECONDS)


def cached_fetch(language, title, number, cache):
    """The response for one article, from the cache when an earlier run already fetched it."""
    path = Path(cache) / f"{number:03d}.raw" if cache else None
    if path and path.exists():
        return path.read_bytes()
    raw = fetch(language, title)
    if path:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(raw)
    time.sleep(PAUSE_SECONDS)
    return raw


def main(arguments):
    parser = argparse.ArgumentParser()
    parser.add_argument("--cache")
    parser.add_argument("--titles")
    parser.add_argument("language")
    parser.add_argument("output")
    parser.add_argument("title", nargs="*")
    options = parser.parse_args(arguments)
    titles = list(options.title)
    if options.titles:
        titles += [line.strip() for line in Path(options.titles).read_text(encoding="utf-8").splitlines()
                   if line.strip()]
    parts = []
    total = 0
    for number, title in enumerate(titles):
        raw = cached_fetch(options.language, title, number, options.cache)
        total += len(raw)
        text = extract_text(raw)
        print(f"{title}: {len(raw):,} bytes, {len(text.split()):,} words")
        parts.append(f"{title}\n\n{text}\n")
    Path(options.output).write_text("\n".join(parts), encoding="utf-8")
    print(f"downloaded {total:,} bytes")


if __name__ == "__main__":
    main(sys.argv[1:])
