"""Run: python coverage.py > coverage.csv (Python 3, standard library)."""
import base64
import csv
import json
import sys
import unicodedata
import urllib.request
import xml.etree.ElementTree as ET
from pathlib import Path

BLOBS = {
    "eng": "a23b138999f3b9645aabec6f82b9618ea59f838c",
    "hin": "2550d0569ca3815d60013b2cd5f291f5229d0b92",
    "kan": "701cd6f263a396f33736cdeb4017f9fc371570bb",
    "tam": "2090fa6a36e3b82d16e0cf621debd7906ba4bbc6",
    "tel": "bdd4644ca11cedb83beae6e74d4573fccdd8cb90"
}
LIMIT = 4096
writer = csv.writer(sys.stdout, lineterminator="\n")
writer.writerow(["language", "article", "utf8_bytes", "end_offset", "complete_at_4096"])
for language, blob in BLOBS.items():
    if len(sys.argv) > 1:
        xml = (Path(sys.argv[1]) / f"udhr_{language}.xml").read_bytes()
    else:
        url = f"https://api.github.com/repos/eric-muller/udhr/git/blobs/{blob}"
        with urllib.request.urlopen(url) as response:
            xml = base64.b64decode(json.load(response)["content"])
    articles = ET.fromstring(xml).findall("{*}article")
    assert [int(a.attrib["number"]) for a in articles] == list(range(1, 31))
    offset = 0
    for number, article in enumerate(articles, 1):
        parts = ["".join(p.itertext()) for p in article.findall(".//{*}para")]
        body = unicodedata.normalize("NFC", " ".join(" ".join(parts).split()))
        assert body
        size = len(body.encode("utf-8"))
        offset += size + int(number > 1)  # One LF between article bodies.
        writer.writerow([language, number, size, offset, int(offset <= LIMIT)])
