#!/usr/bin/env python3
"""复算 LOONTA 公开正文与最终 HTML 哈希；只用 Python 标准库。"""
from html.parser import HTMLParser
from pathlib import Path
from urllib.request import urlopen
import hashlib
import json
import sys
import unicodedata


class ArticleBodyParser(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.depth = 0
        self.seen = False
        self.parts = []

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        classes = attrs.get("class", "").split()
        if tag == "article" and "article-body" in classes:
            self.depth = 1
            self.seen = True
        elif self.depth:
            self.depth += 1

    def handle_endtag(self, tag):
        if self.depth:
            self.depth -= 1

    def handle_data(self, data):
        if self.depth and data.strip():
            self.parts.append(unicodedata.normalize("NFKC", data.strip()))


def body_hash(html_text):
    parser = ArticleBodyParser()
    parser.feed(html_text)
    if not parser.seen:
        raise ValueError("未找到 article.article-body")
    canonical = "\n".join(
        line.strip()
        for part in parser.parts
        for line in part.splitlines()
        if line.strip()
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def main():
    base = sys.argv[1].rstrip("/") if len(sys.argv) > 1 else "https://loonta.com"
    with urlopen(base + "/assets/public-integrity.json", timeout=20) as response:
        manifest = json.load(response)
    failed = []
    for item in manifest["items"]:
        with urlopen(base + item["url"], timeout=20) as response:
            raw = response.read()
        actual_html = hashlib.sha256(raw).hexdigest()
        actual_body = body_hash(raw.decode("utf-8"))
        html_ok = actual_html == item["public_html_sha256"]
        body_ok = actual_body == item["public_body_sha256"]
        print(f"{item['id']}: HTML={'PASS' if html_ok else 'FAIL'} BODY={'PASS' if body_ok else 'FAIL'}")
        if not (html_ok and body_ok):
            failed.append(item["id"])
    if failed:
        print("复算失败：" + ", ".join(failed), file=sys.stderr)
        raise SystemExit(1)
    print(f"ALL_PUBLIC_HASHES_PASS · {len(manifest['items'])} 篇")


if __name__ == "__main__":
    main()
