"""Read-only second-batch HTTP audit that permits proven concurrent human saves."""
from concurrent.futures import ThreadPoolExecutor
from http.cookiejar import CookieJar
import hashlib
import json
from pathlib import Path
import sys
from urllib.request import build_opener, HTTPCookieProcessor

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT)); sys.path.insert(0, str(PROJECT/'scripts'))
from scripts.check_mask_under50_public import fetch
from pallet.cluster_targets import digest
from pallet.mask_review_continuation import audit_snapshot
from pallet.mask_quality_recovery import POSE, fingerprint
from pallet.mask_quota_saved_extension import file_inventory
from pallet.pose_review_geometry import canonical

TASKS = PROJECT/'outputs/pallet_mask_under50_requests_v2'
OUTPUT = PROJECT/'outputs/pallet_mask_under50_v2_acceptance_v2'


def read(path):
    return json.loads(Path(path).read_text())


def require(value, message):
    if not value:
        raise ValueError(message)


def audit(base):
    require(not OUTPUT.exists(), 'Fresh public acceptance output required')
    OUTPUT.mkdir(mode=0o700)
    manifest = read(TASKS/'manifest.json'); seal = read(TASKS/'verification.json')
    before_package = file_inventory(TASKS); config = file_inventory(PROJECT/'configs'); pose_before = fingerprint(POSE)
    require(seal['state'] == 'passed' and seal['manifest_sha256'] == digest(TASKS/'manifest.json'), 'Matching independent seal required')
    plain = build_opener(); authenticated = build_opener(HTTPCookieProcessor(CookieJar()))
    status, raw, _ = fetch(plain, base, '/healthz'); health = json.loads(raw)
    require(status == 200 and health['targets'] == 1550 and health['manual_template_requests'] == 9 and health['editing_enabled'], 'Wrong service')
    def asset(item):
        name, expected = item
        status, raw, headers = fetch(build_opener(), base, '/template-requests/'+name)
        require(status == 200, 'Public asset missing: '+name)
        if name == 'report_zh.html':
            require('少于50份人工轮廓' in raw.decode() and b'mgEditor' in raw and b'under50ScopeNote' in raw, 'Task/editor missing')
        else:
            require(hashlib.sha256(raw).hexdigest() == expected, 'Public asset bytes differ: '+name)
        require(headers.get('x-content-type-options') == 'nosniff' and 'content-security-policy' in headers, 'Protection headers missing')
        return dict(path='/template-requests/'+name, sha256=hashlib.sha256(raw).hexdigest(), status=200)
    with ThreadPoolExecutor(max_workers=4) as pool:
        assets = list(pool.map(asset, manifest['public_assets'].items()))
    drafts = [json.loads(line) for line in (TASKS/'proposals.jsonl').read_text().splitlines()]
    secret = (PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    require(fetch(authenticated, base, '/api/review/login', {'key': secret})[0] == 200, 'Authentication failed')
    reviews = []
    for draft in drafts:
        key = draft['target_key']; status, raw, _ = fetch(authenticated, base, '/api/review/targets/'+key)
        value = json.loads(raw)
        require(status == 200 and value['proposal_polygon'] == draft['polygon'] and value['assistant_preannotation_source']
            and not value['proposal_dependency_stale'], 'Bound draft detail differs')
        review = value['review']
        if review:
            require(review['source_binding'] == value['source_binding'] and review['target_key'] == key
                and review['preannotation_provenance']['worklist_manifest_sha256'] == digest(TASKS/'manifest.json')
                and review['event_kind'] == 'human_mask_gallery_revision', 'Concurrent real save has wrong binding')
            reviews.append(dict(target_key=key, revision=review['revision'], polygon_changed=review['polygon'] != draft['polygon']))
        require(fetch(plain, base, '/api/review/targets/'+key)[0] == 401, 'Editor details publicly exposed')
        status, raw, _ = fetch(plain, base, f'/images/{key}.png')
        require(status == 200 and hashlib.sha256(raw).hexdigest() == draft['preannotation']['image_sha256'], 'Editor alias image differs')
    require(fetch(authenticated, base, '/api/review/logout', {})[0] == 200, 'Logout failed')
    for path in ('/template-requests/internal/shortlist.jsonl', '/template-requests/manifest.json', '/mask_reviews.sqlite3', '/access_key.txt'):
        require(fetch(plain, base, path)[0] == 404, 'Private resource exposed')
    old_services = []
    for directory, count in (('pallet_mask_gallery_managed_v1', 26), ('pallet_mask_under50_managed_v1', 10)):
        url = read(PROJECT/'outputs'/directory/'public_access.json')['public_url']
        status, raw, _ = fetch(plain, url, '/healthz'); value = json.loads(raw)
        require(status == 200 and value['targets'] == 1550 and value['manual_template_requests'] == count, 'Old review service replaced')
        old_services.append(dict(public_url=url, preserved_request_count=count))
    # A genuine user may save while this audit is running. Independently bind
    # every observed raw event to its actual sealed task; never require review
    # to be null or mistake a legitimate save for a test write.
    source_output = PROJECT/'outputs/pallet_mask_continuation_sources_v3'
    _, _, _, _, sources = audit_snapshot(source_output)
    require(config == file_inventory(PROJECT/'configs') and pose_before == fingerprint(POSE), 'Configs/pose changed')
    require(before_package == file_inventory(TASKS), 'Sealed pack changed')
    result = dict(state='passed_public_bytes_and_bound_editor_reads_with_concurrent_human_saves',
        public_url=base+'/template-requests/?batch=under50-v2', request_count=9, class_counts=manifest['class_counts'],
        public_assets_verified=assets, editor_image_aliases_verified=9, authenticated_target_details_verified=9,
        real_saves_observed_during_target_reads=reviews, old_services=old_services,
        source_event_audit_sha256=digest(source_output/'audit.json'),
        source_audit_all_current_events_verified=True, latest_gallery_events_observed=sources['gallery_events'],
        task_verification_sha256=digest(TASKS/'verification.json'), global_configs_unchanged=True,
        production_annotation_requests_sent=0, login_logout_only_posts=True, no_synthetic_human_events=True,
        current_records_not_required_to_stay_unsaved=True, contour_accuracy_certified=False,
        code_sha256=digest(__file__), actual_serving_code_sha256=digest(PROJECT/'scripts/serve_mask_under50_review_v2.py'))
    with (OUTPUT/'public_acceptance.json').open('xb') as stream:
        stream.write(canonical(result)+b'\n')
    print(json.dumps({k: v for k, v in result.items() if k in ('state', 'public_url', 'request_count', 'class_counts')}), flush=True)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__); parser.add_argument('--base'); args = parser.parse_args()
    audit(args.base or read(PROJECT/'outputs/pallet_mask_under50_managed_v2/public_access.json')['public_url'])
