# -*- coding: utf-8 -*-
"""Extract JHU courseleaf program panels (overview / admission / requirements)."""
import io, re, sys, os

BASE = r"D:\work buddy\2026-11-05-14-15-52"


def clean(h):
    h = re.sub(r'<script.*?</script>|<style.*?</style>', ' ', h, flags=re.S | re.I)
    h = re.sub(r'<br[^>]*>|</p>|</h\d>|</li>|</tr>|</td>|</div>', '\n', h, flags=re.I)
    h = re.sub(r'<[^>]+>', ' ', h)
    h = (h.replace("&nbsp;", " ").replace("&amp;", "&").replace("&lt;", "<")
         .replace("&gt;", ">").replace("&#8203;", "").replace("&quot;", '"')
         .replace("&#39;", "'").replace("&rsquo;", "'").replace("&ndash;", "-"))
    h = re.sub(r'[ \t]+', ' ', h)
    h = re.sub(r'\n\s*\n+', '\n', h)
    return h.strip()


def panel(t, pid):
    i = t.find('id="%s"' % pid)
    if i < 0:
        return ""
    j = t.find('</div>', t.find('class="page_content', i)) if 'class="page_content' in t[i:i + 300] else len(t)
    # panels are concatenated: cut at next known container id
    ends = [t.find('id="%s"' % x, i + 10) for x in ("admissiontexttab", "requirementstexttab", "texttab")]
    ends = [e for e in ends if e > 0]
    end = min(ends) if ends else len(t)
    return clean(t[i:end])


def main():
    f = sys.argv[1]
    if not os.path.isabs(f):
        f = os.path.join(BASE, "cache", f)
    t = io.open(f, encoding="utf-8", errors="ignore").read()
    which = sys.argv[2] if len(sys.argv) > 2 else "all"
    for pid, label in (("textcontainer", "OVERVIEW"), ("admissiontextcontainer", "ADMISSION"), ("requirementstextcontainer", "REQUIREMENTS")):
        if which not in ("all", label.lower()):
            continue
        txt = panel(t, pid)
        print("\n===== %s (%d chars) =====" % (label, len(txt)))
        print(txt)


if __name__ == "__main__":
    main()
