from html.parser import HTMLParser
from pathlib import Path
import json
import re
import subprocess

root = Path(__file__).resolve().parent
markdown = (root / 'wms-sso-integration-maintenance.md').read_text()
html = (root / 'wms-sso-integration-maintenance.html').read_text()
rendered = subprocess.check_output(['python3', str(root / 'render_document.py')], text=True)
assert html.rstrip() == rendered.rstrip(), 'HTML must match the Markdown source'


class Structure(HTMLParser):
    def __init__(self):
        super().__init__()
        self.ids = []
        self.links = []
        self.resources = []
        self.headings = 0

    def handle_starttag(self, tag, attributes):
        attributes = dict(attributes)
        if 'id' in attributes:
            self.ids.append(attributes['id'])
        if tag == 'a':
            self.links.append(attributes.get('href', ''))
        if tag in ['script', 'img', 'iframe', 'link']:
            self.resources.append(attributes)
        if tag == 'h2':
            self.headings += 1


structure = Structure()
structure.feed(html)
assert structure.headings == 14
assert len(structure.ids) == len(set(structure.ids))
assert all(link.startswith('#') and link[1:] in structure.ids for link in structure.links)
assert not structure.resources, 'Reading copy must not depend on remote resources'
highlight = re.search(r'<section class="project-switch-highlight"[^>]*>(.*?)</section>', html, re.S)
assert highlight and '更换进销存项目：直接操作清单' in highlight.group(1)
assert 'password_md5' in highlight.group(1) and 'sso_base_url' in highlight.group(1)
assert '系统职责' not in highlight.group(1), 'Red highlight must not extend into other modules'
for block in re.findall(r'```json\n(.*?)\n```', markdown, re.S):
    json.loads(block)
assert markdown.count('```') % 2 == 0
for keyword in ['path=monitor', 'HCGJ_SSO_BASE_URL', 'WmsSsoRefresh', '60 秒', '43200',
                'refresh_if_needed=1', 'refreshAfter', 'refreshFailed', '现场服务器', 'WebView', '环境变量覆盖', '不等于进销存租户']:
    assert keyword in markdown, keyword
repo = root.parents[2] / 'store'
service = (repo / 'application/api/service/WmsSso.php').read_text()
route = (repo / 'application/route.php').read_text()
frontend = (repo / 'public/screen/src/utils/wmsSso.js').read_text()
assert 'https://api.houchuguanjia.com/hcgj-portal/api/sso/login' in service
assert "api/screen/wmsLogin" in route
assert '&path=monitor' in frontend
print('PASS Markdown/HTML parity, 14 linked sections, self-contained HTML, JSON examples and source-contract checks')
