"""Read-only model-native event audit; no GT, quota, gallery or training writer."""
from collections import Counter,defaultdict
from contextlib import closing
import hashlib
import json
from pathlib import Path
import sqlite3
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical,polygon_value

ROOT=PROJECT/'outputs/pallet_mask_model_requests_v1';DB=PROJECT/'outputs/pallet_mask_model_reviews_v1/mask_reviews.sqlite3'


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


def audit(root=ROOT,database=DB):
    root=Path(root);database=Path(database)
    manifest=json.loads((root/'manifest.json').read_text());proposals={r['target_key']:r for r in map(json.loads,(root/'proposals.jsonl').read_text().splitlines())}
    namespace=manifest.get('source_namespace','model-native-v1')
    with closing(sqlite3.connect(database.resolve().as_uri()+'?mode=ro',uri=True)) as db:
        db.execute('PRAGMA query_only=ON');db.execute('BEGIN')
        metadata=dict(db.execute('SELECT key,value FROM metadata'))
        current=dict(db.execute('SELECT target_key,payload FROM reviews'))
        events=list(db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'))
    if metadata.get('worklist_manifest_sha256')!=digest(root/'manifest.json') or metadata.get('source_namespace')!=namespace:raise ValueError('Wrong model worklist store binding')
    histories=defaultdict(list);raw_events=[]
    for event_id,key,revision,raw in events:
        value=json.loads(raw);p=proposals[key];row=p['source']
        template=manifest.get('allow_template_initialization') is True and p.get('initialization',{}).get('kind')=='same_class_template'
        identity={name:row[name] for name in ('target_key','frame_id','split','box_index','bbox','size','source_pcd_sha256')}
        identity.update(formal_manifest_sha256=p['formal_manifest_sha256'],image_sha256=p['model_source_image_sha256'])
        if not (value['target_key']==key and value['revision']==revision==len(histories[key])+1
                and value['event_kind']=='human_model_mask_review' and value['proposal_publication']==namespace
                and value['worklist_manifest_sha256']==digest(root/'manifest.json') and value['base_proposal_id']==sha(p)
                and value['model_provenance']==p['model_provenance'] and value['source']==identity and value['source_binding']==sha(identity)
                and value['human_review_save_action'] is True and value['human_edited'] is True
                and all(value[f] is False for f in ('ground_truth_eligible','automatic_training_eligible','robot_command_eligible','propagation_seed_eligible','human_mask_confirmed','human_pose_confirmed'))
                and value['geometry_changed_from_model']==(False if template else value['polygon']!=p['polygon'])
                and value['accepted_model_without_geometry_change']==(False if template else value['polygon']==p['polygon'])):raise ValueError('Model event binding, provenance or draft-only eligibility differs')
        if manifest.get('allow_template_initialization') is True:
            if not (value.get('initialization_provenance')==p['initialization'] and value.get('image_reuse')==p['image_reuse']
                    and value.get('quality_override_authorized') is True and value.get('quality_certified') is False
                    and value.get('template_initialized')==template
                    and value.get('geometry_changed_from_initialization')==(value['polygon']!=p['polygon'])
                    and value.get('accepted_initialization_without_geometry_change')==(value['polygon']==p['polygon'])):
                raise ValueError('Template/model initialization or duplicate-image source was falsely attributed')
        polygon_value(value['polygon'],*row['size']);histories[key].append(raw)
        if 'class_keypoint_constraint' in p:
            standard=p['class_keypoint_constraint']['standard_count'];actual=len(value['polygon']);editing=value.get('human_keypoint_editing')
            if value.get('class_keypoint_constraint')!=p['class_keypoint_constraint']:
                raise ValueError('Saved class keypoint count or standard binding differs')
            if editing is None:
                if actual!=standard:raise ValueError('Historical fixed-count save differs without explicit human editing policy')
            else:
                previous=json.loads(histories[key][-2])['polygon'] if len(histories[key])>1 else p['polygon']
                expected=dict(policy='human_keypoint_fine_adjustment_add_remove_v1',standard_applies_to='initial_machine_proposal_only',
                    initial_standard_count=standard,actual_saved_count=actual,delta_from_standard=actual-standard,
                    standard_count_matches=actual==standard,previous_saved_or_initial_count=len(previous),point_count_changed_from_previous=actual!=len(previous))
                if editing!=expected:raise ValueError('Human count-change policy/actual count/previous revision trace differs')
        raw_events.append(dict(event_id=event_id,target_key=key,revision=revision,payload_raw_utf8_sha256=hashlib.sha256(raw.encode('utf-8')).hexdigest()))
    if set(current)!=set(histories) or any(histories[k][-1]!=raw for k,raw in current.items()):raise ValueError('Latest model review and append-only history differ')
    actual=Counter(proposals[k]['class_id'] for k in current);edited=Counter(proposals[k]['class_id'] for k,r in current.items() if json.loads(r)['geometry_changed_from_model'])
    human_counts=Counter(proposals[k]['class_id'] for k,r in current.items() if 'class_keypoint_constraint' in proposals[k]
        and len(json.loads(r)['polygon'])!=proposals[k]['class_keypoint_constraint']['standard_count'])
    before=manifest['actual_human_saved_before']
    return dict(state='read_only_real_model_save_provenance_checked_not_quality_release',new_distinct_saved_images=len(current),events=len(events),
        class_distinct_saved=dict(actual),class_geometry_edited=dict(edited),
        class_human_saved_count_different_from_initial_standard=dict(human_counts),
        base_manual_count=manifest.get('base_manual_count',1559),base_plus_real_saved_drafts={c:before[str(c)]+actual[c] for c in range(1,23)},
        remaining_to100_if_saved_reviews_counted={c:max(0,100-before[str(c)]-actual[c]) for c in range(1,23)},
        native_mask_quality_confirmed=False,automatic_training_or_GT_promotion=False,raw_event_hashes=raw_events,
        source_namespace=namespace,manifest_sha256=digest(root/'manifest.json'))


if __name__=='__main__':print(json.dumps(audit(),ensure_ascii=False))
