"""Independently verify direct-manual tasks for real four-point contour classes."""
from collections import Counter,defaultdict
from contextlib import closing
from datetime import datetime,timezone
import hashlib
import json
import math
from pathlib import Path
import re
import sqlite3
import sys
from urllib.parse import urlsplit

import numpy as np
from PIL import Image,ImageDraw

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest,protected_snapshot
from pallet.mask_quota_saved_extension import load_formal_evidence,file_inventory
from pallet.mask_template_refined import QUARANTINE,readonly,read_jsonl,verify_history_preserved
from pallet.mask_template_transfer import rectangle,unchanged_rectangle
from pallet.pose_review_geometry import canonical
from scripts.build_mask_template_requests import database_fingerprint,native_quality

CLASSES=(4,5,7,14,22)
FLAGS=('human_mask_confirmed','human_pose_confirmed','metric_pose_confirmed','ground_truth_eligible',
    'automatic_training_eligible','robot_command_eligible')


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


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


def sha(value):return hashlib.sha256(canonical(value)).hexdigest()


def audit(root,parent):
    manifest=read_json(root/'manifest.json');seal=read_json(parent/'verification.json');pm=read_json(parent/'manifest.json')
    require(seal['state']=='passed' and seal['publication_version']==10 and
        seal['proposals_sha256']==digest(parent/'proposals.jsonl') and seal['manifest_sha256']==digest(parent/'manifest.json'),
        'Need matching independently verified publication 10')
    parent_files=file_inventory(parent);config_before=file_inventory(PROJECT/'configs')
    formal,rows,evidence=load_formal_evidence(pm)
    require(manifest['requests_sha256']==digest(root/'requests.jsonl'),'Task inventory hash differs')
    require(manifest.get('parent_verification_sha256',manifest.get('baseline_verification_sha256',
        manifest.get('parent_verification_binding',{}).get('verification.json')))==digest(parent/'verification.json'),
        'Task package must bind the independently verified expansion')
    inputs=read_json(root/'input_manifest.json')
    frozen=inputs['protected_formal_files']
    require(frozen==protected_snapshot(formal) and len(frozen)==20768 and
        read_json(root/'internal/protected_formal_after.json')==frozen,'Formal files changed')
    expected_config=inputs.get('configuration_sha256',manifest.get('configuration_sha256'))
    require(expected_config==config_before,'Worklist configuration freeze differs')
    previous=read_jsonl(parent/'proposals.jsonl');keys={p['target_key'] for p in previous};frames={p['source']['frame_id'] for p in previous}
    old_requests=[r for d in ('pallet_mask_template_requests_v1','pallet_mask_class10_manual_supplement_v2',
        'pallet_mask_quota_100_requests_v2','pallet_mask_quota_100_final_requests_v2','pallet_mask_remaining_requests_v2')
        for r in read_jsonl(PROJECT/'outputs'/d/'requests.jsonl')]
    frames.update(rows[r['target_key']]['frame_id'] for r in old_requests);protected=set(QUARANTINE)
    snapshots={};stores={};history=defaultdict(list)
    for kind,name,table,live in (('pose','reviews_snapshot.sqlite3','annotations',PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'),
            ('gallery','gallery_reviews_snapshot.sqlite3','reviews',PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')):
        snapshot=parent/name;verify_history_preserved(live,snapshot)
        require(database_fingerprint(live)==database_fingerprint(snapshot,True),'Review source changed since parent freeze')
        snapshots[kind]=(snapshot,live)
        with closing(readonly(snapshot,True)) as db:
            current={k:json.loads(raw) for k,raw in db.execute(f'SELECT target_key,payload FROM {table}')}
            events=list(db.execute('SELECT target_key,payload FROM events ORDER BY id'))
        stores[kind]=current
        if kind=='gallery':protected.update(current);protected.update(k for k,_ in events)
        else:
            for k,raw in events:
                v=json.loads(raw);history[k].append(v)
                if (not unchanged_rectangle(v.get('polygon'),rows[k]) or v.get('state') in ('deleted','deferred','confirmed') or
                        any(v.get(f) for f in FLAGS)):protected.add(k)
            for k,v in current.items():
                if (not unchanged_rectangle(v.get('polygon'),rows[k]) or v.get('state') in ('deleted','deferred','confirmed') or
                        any(v.get(f) for f in FLAGS)):protected.add(k)
    frames.update(rows[k]['frame_id'] for k in protected)
    tasks=read_jsonl(root/'requests.jsonl');counts=Counter(r['class_id'] for r in tasks)
    expected={c:min(10,100-sum(p['class_id']==c for p in previous)) for c in CLASSES}
    expected={c:n for c,n in expected.items() if n>0}
    require(counts==expected and len(tasks)==len({r['target_key'] for r in tasks})==len({r['source']['frame_id'] for r in tasks}),
        'Direct tasks must cover only the declared shortfalls, without duplicate images')
    decisions=read_json(root/'internal/source_visual_decisions.json')
    require(manifest['source_visual_decisions_sha256']==digest(root/'internal/source_visual_decisions.json'),'Visual source decisions changed')
    public={'report_zh.html','report-font.otf','FONT_LICENSE.txt'}
    pose_url=read_json(PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json')['public_url'].rstrip('/')
    for r in tasks:
        k=r['target_key'];row=rows[k];s=r['source']
        require(k not in keys and k not in protected and row['frame_id'] not in frames,'Previously labeled or protected image selected')
        require(row['final_class_id']==r['class_id'] in CLASSES,'Direct task candidate class differs')
        require(all(s.get(f)==row[f] for f in ('target_key','target_id','frame_id','split','group_id','box_index','bbox','size','source_pcd_sha256','policy_id','viewpoint_candidate')), 'Formal source identity differs')
        require(r['original_rectangle']==rectangle(row) and 'polygon' not in r and r['status']=='needs_manual_tracing','Direct task is not a new mask')
        require(all(r.get(f,False) is False for f in (*FLAGS,'accepted_candidate','production_saved','counts_as_completed_annotation')), 'Task claims unsupported confirmation or completion')
        require(r.get('valid_four_point_manual_contour_allowed') is True and r.get('extra_vertices_must_not_be_forced') is True,
            'Valid four-point contours must not be forced to have more vertices')
        v=stores['pose'].get(k)
        require(r['existing_pose_record'] is (v is not None) and r['existing_pose_revision']==(v['revision'] if v else 0) and
            r['existing_pose_payload_sha256']==(sha(v) if v else None),'Existing pose revision binding differs')
        if v:
            require(unchanged_rectangle(v['polygon'],row) and all(unchanged_rectangle(old['polygon'],row) for old in history[k]),'Edited masks may not be requested again')
            require(r.get('existing_pose_current_payload')==v,'Complete existing pose payload must be preserved')
            require(r.get('preserve_existing_pose_until_intentional_human_edit') is True,'Pose preservation missing')
        quality,reason=native_quality(row,evidence);require(reason is None,'Unchanged native-quality gates failed')
        require(all(abs(r['image_quality'][f]-value)<1e-8 for f,value in quality.items()),'Native quality evidence differs')
        require(r['pose_annotation_url']==pose_url+'/?target='+k and urlsplit(r['pose_annotation_url']).scheme=='https','Annotation deep link differs')
        decision=decisions.get(k,{})
        require(decision.get('approved') is True and decision.get('crop_inspected') is True and decision.get('full_image_inspected') is True and
            decision.get('note_zh')==r['source_visual_review_zh'],'Explicit crop/full-image visual review missing')
        image=evidence.image(row['frame_id']);x,y,w,h=(row['bbox'][f] for f in ('x','y','width','height'))
        bounds=[max(0,math.floor(x-max(12,.1*w))),max(0,math.floor(y-max(12,.6*h))),min(image.shape[1],math.ceil(x+w+max(12,.1*w))),min(image.shape[0],math.ceil(y+h+max(12,.6*h)))]
        require(r['crop_native_bounds']==bounds,'Native crop bounds differ')
        l,t,rr,b=bounds;crop=Image.fromarray(image[t:b,l:rr]).convert('RGB');ImageDraw.Draw(crop).rectangle((x-l,y-t,x+w-l,y+h-t),outline=(255,180,40),width=1)
        with Image.open(root/r['contact_crop']) as actual:require(np.array_equal(np.asarray(actual),np.asarray(crop)),'Native crop image differs')
        require(digest(root/r['native_image'])==digest(formal/row['image'])==s['image_sha256'],'Original source image bytes differ')
        public.update((r['contact_crop'],r['native_image']))
    require(set(manifest['public_assets'])==public and all(digest(root/n)==h for n,h in manifest['public_assets'].items()),'Public image/report allowlist differs')
    require(not any(p.suffix in ('.sqlite','.sqlite3','.db') for p in root.rglob('*')),'Private databases must remain in frozen parent evidence only')
    page=(root/'report_zh.html').read_text()
    require('四点' in page and '原矩形' in page and all('id="'+r['target_key']+'"' in page for r in tasks),'Direct-manual instructions/cards missing')
    require(not any(word in page for word in ('current_payload_raw','existing_pose_current_payload','human_event_payload_raw','access_key')), 'Private payload exposed in public report')
    from fontTools.ttLib import TTFont
    with TTFont(root/'report-font.otf') as font:require({ord(c) for c in page if '\u3400'<=c<='\u9fff'}<=set(font.getBestCmap()),'Chinese font glyph missing')
    require(file_inventory(PROJECT/'configs')==config_before and file_inventory(parent)==parent_files and protected_snapshot(formal)==frozen,'Inputs changed during independent worklist audit')
    for snapshot,live in snapshots.values():require(database_fingerprint(live)==database_fingerprint(snapshot,True),'Actual review changed during worklist audit')
    return dict(state='passed',request_count=len(tasks),class_counts=dict(counts),requests_sha256=digest(root/'requests.jsonl'),
        manifest_sha256=digest(root/'manifest.json'),public_assets=manifest['public_assets'],parent_verification_sha256=digest(parent/'verification.json'),
        protected_formal_files_verified=20768,existing_pose_records_preserved=sum(r['existing_pose_record'] for r in tasks),
        native_quality_gates_unchanged=True,valid_four_point_contours_allowed=True,extra_vertices_forbidden=True,
        tasks_counted_as_completed=False,production_annotation_writes=0,automatic_training_eligible=False,robot_command_eligible=False,
        verification_script_sha256=digest(__file__),verified_at=datetime.now(timezone.utc).isoformat())


def main():
    import argparse
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--directory',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_direct_requests_v1')
    parser.add_argument('--parent',type=Path,default=PROJECT/'outputs/pallet_mask_remaining_expand_v1')
    args=parser.parse_args();root=args.directory.resolve();parent=args.parent.resolve()
    require(root.parent==PROJECT/'outputs' and re.fullmatch('pallet_mask_remaining_direct_requests_v[0-9]+',root.name),'Only a fresh direct-manual request directory is allowed')
    seal=root/'independent_verification.json';require(not seal.exists(),'Preserve completed independent worklist seal')
    result=audit(root,parent)
    seal.write_bytes(canonical(result)+b'\n');print(json.dumps({k:v for k,v in result.items() if k!='public_assets'},ensure_ascii=False),flush=True)


if __name__=='__main__':main()
