import re, sys, json
from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit
sys.path.insert(0, str(Path(__file__).parent))
import quality_queue as q

root = Path(__file__).parent
VOID = q.VOID
ALLOWED = {'arts.columbia.edu', 'apply.arts.columbia.edu'}
pages = ['details/col-c5c6e6c.html', 'details/col-c4f6109.html', 'details/col-c4a09cc.html',
         'details/col-c3ec5fe.html', 'details/col-cb6dbda.html']


class Balance(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.stack, self.mismatch, self.unclosed = [], 0, 0
    def handle_starttag(self, tag, attrs):
        if tag not in VOID:
            self.stack.append(tag)
    def handle_startendtag(self, tag, attrs):
        pass
    def handle_endtag(self, tag):
        if tag in VOID:
            return
        if tag in self.stack:
            while self.stack and self.stack[-1] != tag:
                self.stack.pop(); self.unclosed += 1
            if self.stack:
                self.stack.pop()
        else:
            self.mismatch += 1


def main():
    res = {}
    for p in pages:
        src = (root / p).read_text(encoding='utf-8-sig')
        doc = q.Document(src)
        b = Balance(); b.feed(src); b.close()
        hrefs = [n.attrs['href'] for n in doc.root.walk() if 'href' in n.attrs]
        local_bad = [i for i in q.href_issues(root, root / p, doc) if i['code'] == 'missing_local_href']
        outside = sorted({h for h in hrefs if q.external(h) and (urlsplit(h).hostname or '') not in ALLOWED})
        quotes = [n for n in doc.root.walk() if n.tag == 'div' and 'quote' in n.attrs.get('class', '').split()]
        qmiss = sum(1 for n in quotes if '查阅2026-11-06' not in n.text())
        sections = [n.text() for n in doc.root.walk() if n.tag == 'h2']
        res[p] = {
            'sections': sum(1 for s in sections if any(k in s for k in q.SECTIONS)),
            'h2': sections,
            'quote_blocks': len(quotes),
            'quote_dates_missing': qmiss,
            'links_total': len(hrefs),
            'links_external': sum(1 for h in hrefs if q.external(h)),
            'missing_local_href': len(local_bad),
            'outside_domains': outside,
            'tags_mismatch': b.mismatch,
            'tags_unclosed': b.unclosed,
            'stack_left': len(b.stack),
            'title': next((n.text() for n in doc.root.walk() if n.tag == 'title'), ''),
        }
    Path('arts_struct.json').write_text(json.dumps(res, ensure_ascii=False, indent=2), encoding='utf-8')
    for k, v in res.items():
        print(k, 'sections=%d' % v['sections'], 'quotes=%d' % v['quote_blocks'],
              'qtmiss=%d' % v['quote_dates_missing'], 'links=%d' % v['links_total'],
              'localbad=%d' % v['missing_local_href'], 'mismatch=%d' % v['tags_mismatch'],
              'unclosed=%d' % v['tags_unclosed'], 'left=%d' % v['stack_left'],
              'outside=%s' % (v['outside_domains'] or '-'))


main()
