"""Independent identities, checksums, masks, offline JS data and HTTP smoke checks."""
from __future__ import annotations

import argparse
from concurrent.futures import ThreadPoolExecutor
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import sys
import threading
from urllib.parse import quote
from urllib.request import Request, urlopen

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))

from pallet.fork_face_anylabeling import digest, encoded, protected_write, safe_path
from pallet.merge_appearance_classes import read_json, read_jsonl
from pallet.structure_attributes import STRUCTURES, validate_results


def decode_gallery(path):
    text = path.read_text()
    decoder = json.JSONDecoder()
    start = text.index('const rows=')+len('const rows=')
    rows, end = decoder.raw_decode(text[start:])
    rest = text[start+end:]
    if not rest.startswith(',groups='):
        raise ValueError('Unexpected gallery group data layout')
    groups, end = decoder.raw_decode(rest[len(',groups='):])
    rest = rest[len(',groups=')+end:]
    if not rest.startswith(',roots='):
        raise ValueError('Unexpected gallery resource layout')
    roots, _ = decoder.raw_decode(rest[len(',roots='):])
    return rows, groups, roots


def verify(output, artifacts):
    manifest = read_json(output/'output_manifest.json')
    if manifest['state'] != 'complete':
        raise ValueError('Dataset has not completed')
    def check_file(item):
        name, expected = item
        if digest(safe_path(output, name)) != expected:
            raise ValueError(f'Output checksum mismatch: {name}')
    with ThreadPoolExecutor(max_workers=8) as pool:
        list(pool.map(check_file, manifest['files'].items()))
    run = read_json(output/'run_manifest.json')
    source = next(Path(p) for p in run['inputs'] if p.endswith('center_reclassification_v1/targets.jsonl'))
    original, rows = read_jsonl(source), read_jsonl(output/'targets.jsonl')
    rechecks_path = output/'inputs/necessary_visual_rechecks.json'
    rechecks = {r['target_key']: r for r in read_json(rechecks_path)['observations']} if rechecks_path.exists() else {}
    validate_results(original, rows, rechecks)
    summary = read_json(output/'summary.json')
    groups = read_json(output/'groups.json')
    if (len(rows) != sum(summary['states'].values())
            or len(rows) != sum(summary['structures'].values())+summary['states'].get('partial', 0)+summary['states'].get('unknown', 0)
            or len(rows) != sum(g['targets'] for g in groups)
            or len(read_jsonl(output/'seed_targets.jsonl')) != 440):
        raise ValueError('Structure totals or seed identities are inconsistent')
    public, gallery_groups, roots = decode_gallery(output/'gallery.html')
    if len(public) != len(rows) or gallery_groups != groups:
        raise ValueError('Gallery counts disagree with full results')
    resources = set()
    for r in rows:
        resources.add((output/roots['media']/f'{r["target_key"]}.jpg').resolve())
        resources.add((output/roots['dataset']/r['image']).resolve())
        e = r['structure_projection_evidence']
        for path in (e['threshold_mask'], e.get('foreground_mask')):
            if path: resources.add(safe_path(output, path))
        if e.get('pointcloud_evidence'):
            resources.add(safe_path(output, e['pointcloud_evidence']['native_mask']))
    for path in resources:
        if not path.is_file(): raise ValueError(f'Missing gallery resource: {path}')
    for g in groups:
        path = output/f'evidence/class_{g["final_class_id"]:02d}.js'
        text = path.read_text()
        prefix = f'window.structureEvidence=window.structureEvidence||{{}};window.structureEvidence[{g["final_class_id"]}]='
        if not text.startswith(prefix) or not text.endswith(';\n'):
            raise ValueError('Invalid offline evidence script wrapper')
        data = json.loads(text[len(prefix):-2])
        selected = [r for r in rows if r['final_class_id'] == g['final_class_id']]
        if set(data) != {r['target_key'] for r in selected}:
            raise ValueError('Evidence script target identities disagree')
        for r in selected:
            if data[r['target_key']]['support_leg_count'] != r['structure_projection_evidence']['support_leg_count']:
                raise ValueError('Evidence script changed projection values')
    # HEAD requests to every group bundle and representatives from all available
    # combinations / partial states, not a claim of desktop browser interaction.
    picks = []
    for label in (*STRUCTURES.values(), None):
        candidates = [r for r in rows if r['structure_label'] == label]
        picks += candidates[:2]
    picks += [r for r in rows if r['structure_visual_rechecked']]
    picks += [r for r in rows if r['structure_label_source'] == 'pointcloud_mask_projection_fallback'][:4]
    http_paths = {output/'gallery.html', output/'report_zh.html', output/'托盘结构分类结果.xlsx', output/'assets/ReportSans.woff'}
    http_paths |= set(output.glob('evidence/*.js'))
    for r in picks:
        http_paths.add((output/roots['media']/f'{r["target_key"]}.jpg').resolve())
        http_paths.add((output/roots['dataset']/r['image']).resolve())
        e = r['structure_projection_evidence']
        http_paths.add(output/e['threshold_mask'])
        if e.get('foreground_mask'): http_paths.add(output/e['foreground_mask'])
        if e.get('pointcloud_evidence'): http_paths.add(output/e['pointcloud_evidence']['native_mask'])
    class Handler(SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs): super().__init__(*args, directory=str(PROJECT), **kwargs)
        def log_message(self, *args): pass
    server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
    try:
        port = server.server_address[1]
        for path in http_paths:
            url = f'http://127.0.0.1:{port}/'+quote(path.resolve().relative_to(PROJECT).as_posix())
            with urlopen(Request(url, method='HEAD'), timeout=15) as response:
                if response.status != 200: raise ValueError(f'HTTP resource failed: {path}')
    finally:
        server.shutdown(); server.server_close(); thread.join()
    # The installed Playwright driver cannot run on this machine's glibc. Never
    # report the above data/resource checks as GUI or JavaScript execution tests.
    result = {'state': 'passed', 'targets': len(rows), 'groups': len(groups),
        'output_files_sha256_checked': len(manifest['files']), 'referenced_local_resources_exist': len(resources),
        'offline_evidence_bundles_json_checked': len(groups), 'http_head_200_checks': len(http_paths),
        'structure_counts_consistent': True, 'original_fields_unchanged': True,
        'browser_interaction_tested': False,
        'browser_blocker': 'Playwright bundled Node requires GLIBC_2.28; local libc is older, no system browser available',
        'validator_sha256': digest(__file__), 'delivery_manifest_sha256': digest(output/'output_manifest.json')}
    protected_write(artifacts/'verification.json', encoded(result))
    print(json.dumps(result, ensure_ascii=False))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, default=PROJECT/'outputs/pallet_structure_attributes_v1')
    parser.add_argument('--artifacts', type=Path, default=PROJECT/'outputs/pallet_structure_attributes_validation_v1')
    args = parser.parse_args()
    verify(args.output.resolve(), args.artifacts.resolve())


if __name__ == '__main__': main()
