"""Third-batch public bytes and local authenticated details; no annotation POSTs."""
from concurrent.futures import ThreadPoolExecutor
from http.cookiejar import CookieJar
import hashlib
import json
from pathlib import Path
import sys
import time
from urllib.request import build_opener, HTTPCookieProcessor

import requests

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_quota_saved_extension import file_inventory
from pallet.pose_review_geometry import canonical
from pallet.mask_review_continuation import audit_snapshot

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v3'
OUTPUT = PROJECT/'outputs/pallet_mask_under50_v3_acceptance_v1'


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


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


def public_get(base, path):
    # Bounded retries of GET only; never retry or send annotation writes.
    for attempt in range(5):
        try:
            response = requests.get(base+path, timeout=(15, 35))
            if response.status_code not in (502, 503, 504) or attempt == 4:
                return response
        except requests.RequestException:
            if attempt == 4:
                raise
        time.sleep(.5*(attempt+1))


def audit(base):
    require(not OUTPUT.exists(), 'Fresh acceptance output required')
    OUTPUT.mkdir(mode=0o700)
    manifest = read(ROOT/'manifest.json'); seal = read(ROOT/'verification.json')
    package = file_inventory(ROOT); config = file_inventory(PROJECT/'configs')
    require(seal['state'] == 'passed' and seal['manifest_sha256'] == digest(ROOT/'manifest.json'), 'Matching independent seal required')
    n = manifest['request_count']; local = 'http://127.0.0.1:3397'
    response = public_get(base, '/healthz'); health = response.json()
    require(response.status_code == 200 and health['targets'] == 1550 and health['manual_template_requests'] == n
        and health['editing_enabled'], 'Wrong supplementary service')
    def asset(item):
        name, expected = item; response = public_get(base, '/template-requests/'+name)
        require(response.status_code == 200, 'Missing public asset: '+name)
        if name == 'report_zh.html':
            require('少于50份人工轮廓' in response.content.decode() and b'mgEditor' in response.content
                and b'under50ScopeNote' in response.content, 'Wrong task page/editor')
        else:
            require(hashlib.sha256(response.content).hexdigest() == expected, 'Wrong public bytes: '+name)
        require(response.headers.get('x-content-type-options') == 'nosniff' and response.headers.get('content-security-policy'), 'Protection headers missing')
        return dict(path='/template-requests/'+name, bytes=len(response.content), sha256=hashlib.sha256(response.content).hexdigest())
    with ThreadPoolExecutor(max_workers=4) as pool:
        assets = list(pool.map(asset, manifest['public_assets'].items()))
    drafts = [json.loads(s) for s in (ROOT/'proposals.jsonl').read_text().splitlines()]
    auth = build_opener(HTTPCookieProcessor(CookieJar()))
    secret = (PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    require(fetch(auth, local, '/api/review/login', {'key': secret})[0] == 200, 'Local authentication failed')
    saved = []
    for draft in drafts:
        key = draft['target_key']; status, raw, _ = fetch(auth, local, '/api/review/targets/'+key); detail = json.loads(raw)
        require(status == 200 and detail['proposal_polygon'] == draft['polygon'] and detail['assistant_preannotation_source']
            and not detail['proposal_dependency_stale'], 'Bound editable draft differs')
        if detail['review']:
            review = detail['review']; require(review['preannotation_provenance']['worklist_manifest_sha256'] == digest(ROOT/'manifest.json'), 'Concurrent save binding differs')
            saved.append(dict(target_key=key, revision=review['revision']))
        response = public_get(base, f'/images/{key}.png')
        require(response.status_code == 200 and hashlib.sha256(response.content).hexdigest() == draft['preannotation']['image_sha256'], 'Editor image alias changed')
    require(fetch(auth, local, '/api/review/logout', {})[0] == 200, 'Local logout failed')
    denied = ['/template-requests/internal/shortlist.jsonl', '/template-requests/manifest.json', '/mask_reviews.sqlite3', '/access_key.txt']
    for path in denied:
        require(public_get(base, path).status_code == 404, 'Private resource exposed')
    require(public_get(base, '/api/review/targets/'+drafts[0]['target_key']).status_code == 401, 'Public editor detail lacks auth')
    old_health = []
    for directory, count in (('pallet_mask_gallery_managed_v1', 26), ('pallet_mask_under50_managed_v1', 10), ('pallet_mask_under50_managed_v2', 9)):
        old_base = read(PROJECT/'outputs'/directory/'public_access.json')['public_url']
        response = public_get(old_base, '/healthz'); value = response.json()
        require(response.status_code == 200 and value['manual_template_requests'] == count and value['targets'] == 1550, 'Old service replaced')
        old_health.append(dict(public_url=old_base, request_count=count))
    source_out = PROJECT/'outputs/pallet_mask_continuation_sources_v5'
    audit_snapshot(source_out)
    require(package == file_inventory(ROOT) and config == file_inventory(PROJECT/'configs'), 'Sealed tasks/configs changed')
    result = dict(state='passed_public_bytes_and_local_authenticated_editor_binding',
        public_url=base+'/template-requests/?batch=under50-v3', request_count=n, class_counts=manifest['class_counts'],
        public_assets_verified=assets, editor_image_aliases_verified=n, local_authenticated_details_verified=n,
        public_unauthenticated_details_denied=True, private_paths_denied=len(denied), old_services_preserved=old_health,
        actual_saves_observed_during_reads=saved, current_human_event_audit_sha256=digest(source_out/'audit.json'),
        task_verification_sha256=digest(ROOT/'verification.json'), production_annotation_requests_sent=0,
        native_contour_accuracy_certified=False, public_authenticated_browser_not_tested=True,
        code_sha256=digest(__file__), serving_code_sha256=digest(PROJECT/'scripts/serve_mask_under50_review_v3.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__':
    audit(read(PROJECT/'outputs/pallet_mask_under50_managed_v3/public_access.json')['public_url'])
