#!/usr/bin/env python3
"""Pulls the text of WCAG 2.2 success criteria 1.2.1 to 1.2.5 and some definitions out of a saved copy of https://www.w3.org/TR/WCAG22/,
and the "no additional audio description" note out of a saved copy of the Understanding page for 1.2.5.
Usage: python3 extract-wcag.py wcag22.html understanding-1.2.5.html > wcag-quotes.json
       python3 extract-wcag.py --selftest"""
import html, json, re, sys

IDS = {
    "1.2.1": "audio-only-and-video-only-prerecorded",
    "1.2.2": "captions-prerecorded",
    "1.2.3": "audio-description-or-media-alternative-prerecorded",
    "1.2.4": "captions-live",
    "1.2.5": "audio-description-prerecorded",
}
TERMS = ["captions", "alternative-for-time-based-media", "synchronized-media", "media-alternative-for-text", "audio-only", "video-only", "audio-descriptions"]
NOTE_START = "Note For 1.2.3, 1.2.5, and 1.2.7,"

def txt(s):
    s = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", s))).strip()
    return s.replace(" ,", ",").replace(" .", ".").replace(" :", ":")

def criteria(page):
    out = {}
    for num, sid in IDS.items():
        m = re.search(r'<section[^>]*id="%s".*?</section>' % sid, page, re.S)
        if not m:
            continue
        mm = re.search(r"\(Level (A+)\)\s*(.*)$", txt(m.group(0)))
        if mm:
            out[num] = {"level": mm.group(1), "text": mm.group(2)}
    return out

def terms(page):
    out = {}
    for t in TERMS:
        m = re.search(r'<dt[^>]*>\s*<dfn[^>]*id="dfn-%s".*?</dd>' % t, page, re.S) or re.search(r'<dt[^>]*id="dfn-%s".*?</dd>' % t, page, re.S)
        if m:
            out[t] = txt(m.group(0))
    return out

def note(page):
    body = txt(page)
    i = body.find(NOTE_START)
    if i < 0:
        return None
    return body[i + 5:].split(" 1.2.3 Audio Description or Media Alternative (Prerecorded), 1.2.5")[0].strip()

def read(path):
    try:
        t = open(path, encoding="utf-8", errors="replace").read().replace("\r", "")
    except OSError as e:
        sys.exit("cannot read %s: %s" % (path, e.strerror))
    if not t.strip():
        sys.exit("empty file: %s" % path)
    return t

def selftest():
    sample = '<section id="captions-live"><h4>Success Criterion 1.2.4 Captions (Live) (Level AA)</h4><p>Captions are  provided for all live audio.</p></section>'
    got = criteria(sample)
    assert got["1.2.4"]["level"] == "AA" and got["1.2.4"]["text"] == "Captions are provided for all live audio.", got
    n = note("<p>Note For 1.2.3, 1.2.5, and 1.2.7, if all is in audio, no description is necessary. 1.2.3 Audio Description or Media Alternative (Prerecorded), 1.2.5 more</p>")
    assert n == "For 1.2.3, 1.2.5, and 1.2.7, if all is in audio, no description is necessary.", n
    print("selftest ok")

if __name__ == "__main__":
    if sys.argv[1:] == ["--selftest"]:
        selftest(); sys.exit(0)
    if len(sys.argv) != 3:
        sys.exit("usage: python3 extract-wcag.py wcag22.html understanding-1.2.5.html > wcag-quotes.json")
    res = {"criteria": criteria(read(sys.argv[1])), "terms": terms(read(sys.argv[1])), "note_no_description": note(read(sys.argv[2]))}
    if len(res["criteria"]) != len(IDS):
        sys.exit("found %d of %d criteria: is the first file the WCAG 2.2 page?" % (len(res["criteria"]), len(IDS)))
    if not res["note_no_description"]:
        sys.exit("the note about audio description was not found: is the second file the Understanding page for 1.2.5?")
    print(json.dumps(res, indent=2, ensure_ascii=False))
