"""Read-only HTTP acceptance of the isolated under-50 review publication.

Authentication is exercised without recording credentials/cookies or saving any
production annotation. Save/error regression tests must use isolated stores.
"""
import hashlib
from http.cookiejar import CookieJar
import json
from pathlib import Path
import sys
from urllib.error import HTTPError
from urllib.request import HTTPCookieProcessor, Request, build_opener

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from pallet.cluster_targets import digest
from pallet.mask_quality_recovery import fingerprint, POSE, GALLERY
from pallet.mask_quota_saved_extension import file_inventory
from pallet.pose_review_geometry import canonical
from review_http_retry import open_checked, RETRIES

ROOT = PROJECT/'outputs/pallet_mask_under50_requests_v1'
MANAGED = PROJECT/'outputs/pallet_mask_under50_managed_v1'
OUTPUT = PROJECT/'outputs/pallet_mask_under50_acceptance_v3'


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


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


def fetch(opener, base, path, data=None):
    headers = {'Content-Type': 'application/json', 'X-Review-Request': '1'} if data is not None else {}
    request = Request(base+path, headers=headers, data=canonical(data) if data is not None else None)
    try:
        operation = open_checked(request, opener=opener, timeout=40) if data is None or path == '/api/review/login' else opener.open(request, timeout=30)
        with operation as response:
            return response.status, response.read(), {k.lower(): v for k, v in response.headers.items()}
    except HTTPError as error:
        return error.code, error.read(), {k.lower(): v for k, v in error.headers.items()}


def audit(base, output=OUTPUT):
    output = Path(output).resolve()
    require(not output.exists() and output.parent == PROJECT/'outputs', 'Fresh acceptance output required')
    output.mkdir(mode=0o700)
    manifest = read(ROOT/'manifest.json'); inputs = read(ROOT/'input_manifest.json')
    seal = read(ROOT/'verification.json')
    require(seal['state'] == 'passed' and seal['manifest_sha256'] == digest(ROOT/'manifest.json'), 'Task seal differs')
    before = {n: fingerprint(p) for n, p in (('pose', POSE), ('gallery', GALLERY))}
    config = file_inventory(PROJECT/'configs'); package = file_inventory(ROOT)
    plain = build_opener(); assets = []; auth = build_opener(HTTPCookieProcessor(CookieJar()))
    status, raw, _ = fetch(plain, base, '/healthz'); health = json.loads(raw)
    require(status == 200 and health['targets'] == 1550 and health['publication_version'] == 15
        and health['manual_template_requests'] == manifest['request_count'] and health['editing_enabled'], 'Health identity differs')
    for name, expected in manifest['public_assets'].items():
        status, raw, headers = fetch(plain, base, '/template-requests/'+name)
        if name == 'report_zh.html':
            require(status == 200 and '少于50份人工轮廓' in raw.decode() and b'mgEditor' in raw, 'New task page/editor missing')
        else:
            require(status == 200 and hashlib.sha256(raw).hexdigest() == expected, 'Public asset bytes differ: '+name)
        require(headers.get('x-content-type-options') == 'nosniff' and 'content-security-policy' in headers, 'Response protections missing')
        assets.append(dict(path='/template-requests/'+name, status=status, sha256=hashlib.sha256(raw).hexdigest()))
    proposals = [json.loads(line) for line in (ROOT/'proposals.jsonl').read_text().splitlines()]
    for proposal in proposals:
        key = proposal['target_key']; status, raw, _ = fetch(plain, base, f'/images/{key}.png')
        require(status == 200 and hashlib.sha256(raw).hexdigest() == proposal['preannotation']['image_sha256'], 'Editor image alias differs')
        require(fetch(plain, base, f'/api/review/targets/{key}')[0] == 401, 'Unauthenticated editor data exposed')
    # Credentials and Set-Cookie are intentionally never written to receipts.
    secret = (PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    require(fetch(auth, base, '/api/review/login', {'key': secret})[0] == 200, 'Editing authentication failed')
    for proposal in proposals:
        status, raw, _ = fetch(auth, base, '/api/review/targets/'+proposal['target_key']); detail = json.loads(raw)
        require(status == 200 and detail['proposal_polygon'] == proposal['polygon'] and detail['assistant_preannotation_source']
            and not detail['proposal_dependency_stale'] and detail['review'] is None, 'Fresh bound preannotation detail differs')
    require(fetch(auth, base, '/api/review/logout', {})[0] == 200, 'Logout failed')
    denied = ['/template-requests/internal/shortlist.jsonl', '/template-requests/input_manifest.json', '/template-requests/proposals.jsonl',
        '/template-requests/manifest.json', '/mask_reviews.sqlite3', '/access_key.txt', '/configs/active_pose_review.json']
    for path in denied:
        require(fetch(plain, base, path)[0] == 404, 'Private publication path exposed: '+path)
    old_base = read(PROJECT/'outputs/pallet_mask_gallery_managed_v1/public_access.json')['public_url']
    status, raw, _ = fetch(plain, old_base, '/healthz'); old_health = json.loads(raw)
    require(status == 200 and old_health['targets'] == 1550 and old_health['manual_template_requests'] == 26,
        'Existing gallery/v3 service must remain unchanged')
    require(before == {n: fingerprint(p) for n, p in (('pose', POSE), ('gallery', GALLERY))}, 'HTTP acceptance wrote an annotation')
    require(config == inputs['configuration_sha256'] == file_inventory(PROJECT/'configs'), 'Global configurations changed')
    require(package == file_inventory(ROOT), 'Immutable task evidence changed during public audit')
    result = dict(state='passed_read_only_public_acceptance', public_url=base+'/template-requests/?batch=under50-v1',
        request_count=len(proposals), class_counts=manifest['class_counts'], public_assets=assets,
        editor_image_aliases_verified=len(proposals), authenticated_target_details_verified=len(proposals),
        private_paths_denied=len(denied), existing_v3_service_preserved=True,
        task_manifest_sha256=digest(ROOT/'manifest.json'), task_verification_sha256=digest(ROOT/'verification.json'),
        source_fingerprints=before, global_configuration_sha256=config, production_annotation_writes=0,
        human_events_created=0, contour_accuracy_certified=False, real_iPhone_Safari_tested=False,
        code_sha256=digest(__file__), serving_code_sha256=digest(PROJECT/'scripts/serve_mask_under50_review.py'),
        runtime_scope_notice_added_without_changing_sealed_task_page=True, bounded_transport_retries=RETRIES)
    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', 'production_annotation_writes')}), flush=True)
    return result


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--base'); parser.add_argument('--output', type=Path, default=OUTPUT)
    args = parser.parse_args()
    audit(args.base or read(MANAGED/'public_access.json')['public_url'], args.output)
