"""Verify local/public pose service without writing any production annotation."""
from __future__ import annotations

import hashlib
from http.cookiejar import CookieJar
import json
from pathlib import Path
import sys
from urllib.error import HTTPError
from urllib.request import build_opener,HTTPCookieProcessor,Request,urlopen

PROJECT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import protected_snapshot


def main():
    status=json.loads((PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json').read_text())
    key=(PROJECT/status['access_key_file']).read_text().strip()
    out=PROJECT/'outputs/pallet_pose_review_validation_v1';out.mkdir(exist_ok=True)
    reports=[]
    for base in (status['local_url'],status['public_url']):
        jar=CookieJar();opener=build_opener(HTTPCookieProcessor(jar))
        def get(path,headers=None):return opener.open(Request(base+path,headers=headers or {}),timeout=45)
        def post(path,data,headers=None):
            return opener.open(Request(base+path,data=json.dumps(data).encode(),headers={
                'Content-Type':'application/json','X-Review-Request':'1',**(headers or {})}),timeout=45)
        assert json.load(get('/healthz'))['service']=='pallet_pose_review'
        for path in ('/api/bootstrap','/api/queue','/media/51146063f60534e0d7130f7c','/api/export?format=jsonl'):
            try:get(path);raise AssertionError('Unauthenticated access allowed')
            except HTTPError as exc:assert exc.code==401
        login=post('/api/login',{'key':key});assert json.load(login)['ok']
        cookie=login.headers['Set-Cookie'];assert 'HttpOnly' in cookie and 'SameSite=Strict' in cookie
        if base.startswith('https'):assert '; Secure' in cookie
        boot=json.load(get('/api/bootstrap'));assert boot['stats']['total']==12344
        detail=json.load(get('/api/targets/51146063f60534e0d7130f7c'))
        image=get(detail['image_url']);raw=image.read();etag=image.headers['ETag']
        assert hashlib.sha256(raw).hexdigest() in detail['image_url']
        try:get(detail['image_url'],{'If-None-Match':etag});raise AssertionError('ETag ignored')
        except HTTPError as exc:assert exc.code==304
        meta=json.load(post('/api/geometry/51146063f60534e0d7130f7c',{
            'polygon':detail['initial_polygon'],'sensor':detail['sensor']}))
        cloud=get('/cloud/51146063f60534e0d7130f7c/'+meta['token']).read()
        assert len(cloud)==meta['preview_points']*5*4 and meta['roi_points']>0
        try:post('/api/login',{'key':key},{'Origin':'https://not-this-site.invalid'});raise AssertionError('CSRF allowed')
        except HTTPError as exc:assert exc.code==403
        after=json.load(get('/api/bootstrap'))
        assert boot['stats']==after['stats']
        reports.append({'url':base,'state':'passed','targets':boot['stats']['total'],
            'stats_unchanged':True,'unauthenticated_data_denied':True,'login_cookie_secure':base.startswith('https'),
            'cross_site_POST_rejected':True,'original_image_hash_verified':True,'image_ETag_304':True,
            'real_cloud_preview_bytes':len(cloud),'ROI_measured_points':meta['roi_points'],
            'production_annotation_writes':0})
    dataset=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    original=json.loads((PROJECT/'outputs/pallet_pose_human_review_v1/protected_formal_snapshot.json').read_text())
    assert protected_snapshot(dataset)==original
    with urlopen('http://127.0.0.1:3389/healthz',timeout=10) as response:
        assert json.load(response)['status']=='ok'
    report={'state':'passed','checks':reports,'protected_formal_files_unchanged':len(original),
        'existing_structure_review_3389_healthy':True,'existing_structure_review_database_accessed':False,
        'production_pose_annotation_writes':0,'public_service_save_test':'save/confirm/export tested only on isolated equivalent server',
        'temporary_Cloudflare_URL':True,'boot_autostart_configured':False}
    (out/'deployment_verification.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps(report,ensure_ascii=False))


if __name__=='__main__':main()
