#!/usr/bin/env python3
"""Check the shareable knowledge package independently of the source machine."""

import csv
import hashlib
import json
import re
import sys
import zipfile
from html.parser import HTMLParser
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
PACKAGE = ROOT / 'modules/product/products/food-safety/knowledge'
REPORT = Path(__file__).with_name('validation.json')


class Links(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links = []

    def handle_starttag(self, tag, attrs):
        self.links.extend(value for key, value in attrs if key in {'href', 'src'} and value)


failures = []
links_checked = 0
current_files = [p for p in PACKAGE.rglob('*') if p.is_file() and 'sources' not in p.relative_to(PACKAGE).parts and p.suffix in {'.md', '.html'}]
current_files += [ROOT / 'standards-stack/agent-skills/skills/food-safety-product-design/SKILL.md']

for file in current_files:
    text = file.read_text(encoding='utf-8')
    if re.search(r'/Users/[^/\s]+/', text):
        failures.append(f'Personal absolute path in current page: {file.relative_to(ROOT)}')
    if file.suffix == '.html':
        parser = Links()
        parser.feed(text)
        targets = parser.links
    else:
        targets = re.findall(r'\]\((<[^>]+>|[^\s)]+)(?:\s+"[^"\n]*")?\)', text)
    for target in targets:
        target = target.strip('<>')
        if not target or target.startswith('#') or re.match(r'^[a-zA-Z][a-zA-Z0-9+.-]*:', target):
            continue
        target = target.split('#')[0].split('?')[0]
        target = re.sub(r':\d+$', '', target)
        resolved = (file.parent / target).resolve()
        links_checked += 1
        if not resolved.exists():
            failures.append(f'Broken link: {file.relative_to(ROOT)} -> {target}')

with (PACKAGE / 'sources/source-inventory.csv').open(encoding='utf-8', newline='') as handle:
    sources = list(csv.DictReader(handle))
snapshots = [row for row in sources if row['state'] == 'snapshot']
for row in snapshots:
    file = ROOT / row['captured_path']
    if not file.exists():
        failures.append(f'Missing snapshot: {row["captured_path"]}')
    elif hashlib.sha256(file.read_bytes()).hexdigest() != row['snapshot_sha256']:
        failures.append(f'Snapshot hash mismatch: {row["captured_path"]}')

maps = list((PACKAGE / 'sources').rglob('*.xmind'))
for file in maps:
    with zipfile.ZipFile(file) as archive:
        if 'content.json' in archive.namelist():
            json.loads(archive.read('content.json'))
        elif 'content.xml' not in archive.namelist():
            failures.append(f'Unrecognized XMind content: {file.name}')
    if not file.with_name(file.name + '.md').exists():
        failures.append(f'Missing XMind text companion: {file.name}')

with (PACKAGE / 'threads/thread-coverage.csv').open(encoding='utf-8', newline='') as handle:
    threads = list(csv.DictReader(handle))
if len({row['thread_id'] for row in threads}) != len(threads):
    failures.append('Duplicate thread IDs')
for row in threads:
    if not (PACKAGE / 'threads' / (row['thread_id'] + '.md')).exists():
        failures.append(f'Missing compiled thread record: {row["thread_id"]}')

expected_prds = ['首页', '学校与食堂', '预警处理', '检查任务', '整改督办', '食安过程监管', '报表记录', '系统设置']
for index, title in enumerate(expected_prds, 1):
    file = PACKAGE / f'sources/school-design/07_PRD/分模块PRD/PRD-{index:02}_{title}_完整PRD_v1.0.md'
    if not file.exists():
        failures.append(f'Missing current PRD: {file.name}')

postman = json.loads((PACKAGE / 'sources/iot/integration/LH_ACCESS_DEMO_SANITIZED.postman_collection.json').read_text())
if any(variable.get('value') for variable in postman.get('variable', [])):
    failures.append('Postman variables contain non-empty values')

known_secrets = []
if len(sys.argv) > 1:
    config = Path(sys.argv[1])
    if config.exists():
        for line in config.read_text().splitlines():
            if re.match(r'^[A-Z_]+=', line):
                value = line.split('=', 1)[1].strip("'\"")
                if len(value) > 8:
                    known_secrets.append(value)

for file in PACKAGE.rglob('*'):
    if not file.is_file():
        continue
    if file.suffix == '.xmind':
        with zipfile.ZipFile(file) as archive:
            bodies = [archive.read(name).decode('utf-8', errors='ignore') for name in archive.namelist() if name.endswith(('.json', '.xml'))]
    else:
        bodies = [file.read_bytes().decode('utf-8', errors='ignore')]
    for text in bodies:
        if any(secret in text for secret in known_secrets) or re.search(r'Cpt@\d+|-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----', text):
            failures.append(f'Secret value detected: {file.relative_to(ROOT)}')
        if re.search(r'^(<<<<<<<|=======|>>>>>>>)', text, re.M):
            failures.append(f'Conflict marker: {file.relative_to(ROOT)}')

report = {
    'date': '2026-10-26', 'scope': 'portable core pages, snapshots, thread records, mind maps and sanitized collection',
    'current_pages': len(current_files), 'links_checked': links_checked,
    'snapshots_hash_checked': len(snapshots), 'source_records': len(sources),
    'maps_readable': len(maps), 'thread_records': len(threads),
    'thread_summary_turns': sum(int(row['turns_read']) for row in threads),
    'known_secret_scan_enabled': bool(known_secrets),
    'limitations': ['Thread tools return bounded turn summaries, not full raw conversations', 'Some thread summary pages unavailable; see coverage CSV', 'Snapshot-internal historical links retain source context and are not current navigation', 'No production, supplier-device, regulatory-currency or live-Yunxiao verification'],
    'failures': failures, 'passed': not failures,
}
REPORT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
sys.exit(0 if report['passed'] else 1)
