"""Byte/auth/isolation checks; real saves go only to a separate test database."""
from contextlib import closing
import hashlib
from http.cookiejar import CookieJar
from http.server import ThreadingHTTPServer
import json
from pathlib import Path
import sqlite3
import sys
import threading
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 pallet.mask_nonconforming_review import NonconformingGallery, NonconformingHandler, FALSE_FLAGS
from pallet.mask_quality_recovery import POSE, GALLERY, fingerprint
from pallet.mask_quota_saved_extension import file_inventory
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical
from scripts.check_mask_under50_public import fetch
from scripts.check_mask_under50_public_v3 import public_get


def check():
    root = PROJECT/'outputs/pallet_mask_nonconforming_requests_v1'
    out = PROJECT/'outputs/pallet_mask_nonconforming_http_acceptance_v1'
    test = PROJECT/'outputs/pallet_mask_nonconforming_reviews_http_acceptance_v1'
    if out.exists() or test.exists():
        raise ValueError('Fresh HTTP acceptance and isolated test-store directories required')
    out.mkdir(mode=0o700)
    before = {kind: fingerprint(path) for kind, path in (('pose', POSE), ('gallery', GALLERY))}
    config = file_inventory(PROJECT/'configs'); package = file_inventory(root)
    secret = (PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip()
    gallery = NonconformingGallery(root, test, secret)
    server = ThreadingHTTPServer(('127.0.0.1', 0), NonconformingHandler); server.gallery = gallery; server.daemon_threads = True
    thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
    localtest = f'http://127.0.0.1:{server.server_port}'; keys = list(gallery.proposals)
    auth = build_opener(HTTPCookieProcessor(CookieJar()))
    try:
        assert fetch(auth, localtest, '/api/review/targets/'+keys[0])[0] == 401
        assert fetch(auth, localtest, '/api/review/login', {'key': secret})[0] == 200
        details = []
        for key in keys:
            status, raw, _ = fetch(auth, localtest, '/api/review/targets/'+key); detail = json.loads(raw)
            assert status == 200 and detail['proposal_polygon'] == [] and detail['no_reliable_preannotation']
            assert detail['source_quality'] == 'nonconforming' and not detail['counts_toward_under50']
            details.append(detail)
        detail = details[0]; key = keys[0]
        data = dict(binding=detail['binding'], source_binding=detail['source_binding'], proposal_id=detail['proposal_id'],
            expected_revision=0, reviewer='isolated acceptance', note='test store only', quality_decision='untraceable', polygon=[])
        status, raw, _ = fetch(auth, localtest, '/api/review/annotations/'+key, data)
        assert status == 200 and json.loads(raw)['review']['polygon'] == []
        assert fetch(auth, localtest, '/api/review/export/'+key+'/mask.png')[0] == 400
        assert fetch(auth, localtest, '/api/review/annotations/'+key, data)[0] == 409
        box = gallery.proposals[key]['source']['bbox']; x, y, w, h = (box[k] for k in ('x', 'y', 'width', 'height'))
        data.update(expected_revision=1, quality_decision='redrawn_pending_quality_check', polygon=[[x+2, y+2], [x+w-2, y+2], [x+w-2, y+h-2], [x+2, y+h-2]])
        data.update(dict.fromkeys(FALSE_FLAGS, True))
        status, raw, _ = fetch(auth, localtest, '/api/review/annotations/'+key, data); review = json.loads(raw)['review']
        assert status == 200 and all(review[field] is False for field in FALSE_FLAGS)
        assert fetch(auth, localtest, '/api/review/export/'+key+'/mask.png')[0] == 200
        status, raw, _ = fetch(auth, localtest, '/api/review/export/'+key+'/labelme.json'); exported = json.loads(raw)
        assert status == 200 and exported['flags']['nonconforming'] is True and exported['flags']['counts_toward_under50'] is False
        data.update(expected_revision=2, quality_decision='untraceable', polygon=[], restored_from_revision=1)
        assert fetch(auth, localtest, '/api/review/annotations/'+key, data)[0] == 200
        assert len(gallery.editor.store.history(key)) == 3 and gallery.editor.store.history(key)[0]['restored_from_revision'] == 1
        assert fetch(auth, localtest, '/api/review/targets/'+'f'*24)[0] == 404
        assert fetch(auth, localtest, '/api/review/logout', {})[0] == 200
    finally:
        server.shutdown(); server.server_close(); thread.join(timeout=5)
    # Production endpoint: only read and local login/logout; never annotations.
    base = json.loads((PROJECT/'outputs/pallet_mask_nonconforming_managed_v1/public_access.json').read_text())['public_url']
    response = public_get(base, '/healthz'); health = response.json()
    assert response.status_code == 200 and health['service'] == 'pallet_mask_nonconforming_review' and health['counts_toward_under50'] is False
    manifest = json.loads((root/'manifest.json').read_text()); public = []
    for name, expected in manifest['public_assets'].items():
        response = public_get(base, '/'+name); assert response.status_code == 200
        if name == 'report_zh.html':
            assert '不合格样本'.encode() in response.content and b'mgDrawMode' in response.content
        else:
            assert hashlib.sha256(response.content).hexdigest() == expected
        assert response.headers.get('x-content-type-options') == 'nosniff' and response.headers.get('content-security-policy')
        public.append(dict(path=name, bytes=len(response.content), actual_sha256=hashlib.sha256(response.content).hexdigest()))
    for name in ('/manifest.json', '/proposals.jsonl', '/private/exception_authorization.json', '/mask_reviews.sqlite3', '/access_key.txt', '/internal/inspection_targets.jsonl'):
        assert public_get(base, name).status_code == 404
    assert public_get(base, '/api/review/targets/'+keys[0]).status_code == 401
    auth = build_opener(HTTPCookieProcessor(CookieJar()))
    assert fetch(auth, 'http://127.0.0.1:3401', '/api/review/login', {'key': secret})[0] == 200
    for key in keys:
        status, raw, _ = fetch(auth, 'http://127.0.0.1:3401', '/api/review/targets/'+key); detail = json.loads(raw)
        assert status == 200 and detail['proposal_polygon'] == [] and detail['source_quality'] == 'nonconforming'
    assert fetch(auth, 'http://127.0.0.1:3401', '/api/review/logout', {})[0] == 200
    old = []
    for port, count in ((3393, 26), (3395, 10), (3396, 9), (3397, 7), (3398, 6), (3399, 4), (3400, 32)):
        status, raw, _ = fetch(build_opener(), f'http://127.0.0.1:{port}', '/healthz'); value = json.loads(raw)
        assert status == 200 and value['targets'] == 1550 and value['manual_template_requests'] == count
        old.append(dict(port=port, requests=count))
    assert config == file_inventory(PROJECT/'configs') and package == file_inventory(root)
    after = {kind: fingerprint(path) for kind, path in (('pose', POSE), ('gallery', GALLERY))}
    assert before == after, 'Do not conflate concurrent real revisions with test-store events'
    with closing(sqlite3.connect((PROJECT/'outputs/pallet_mask_nonconforming_reviews_v1/mask_reviews.sqlite3').resolve().as_uri()+'?mode=ro', uri=True)) as db:
        current_exceptions = db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
    value = dict(state='passed_http_auth_assets_and_isolated_save_contract_not_UI_or_quality', public_url=base,
        task_count=7, public_assets=public, blank_proposal_seeds_verified=7, test_store=str(test.relative_to(PROJECT)),
        isolated_test_events=3, production_annotation_requests_sent=0, production_sources_unchanged=True,
        live_exception_events_observed=current_exceptions, old_services_preserved=old, flags_remain_ineligible=True,
        original_rejection_reasons_preserved=True, source_quality='nonconforming', counts_toward_under50=False,
        qualified_preannotations=0, real_Safari_not_tested=True, browser_UI_acceptance_not_passed=True,
        manifest_sha256=digest(root/'manifest.json'), code_sha256=digest(__file__))
    with (out/'http_acceptance.json').open('xb') as stream:
        stream.write(canonical(value)+b'\n')
    print(json.dumps(dict(state=value['state'], url=base, tasks=7, isolated_test_events=3, production_annotation_requests_sent=0)), flush=True)


if __name__ == '__main__':
    check()
