"""Separate assistant-drawn review tasks, never accepted transfer candidates or human saves."""
from contextlib import closing
import hashlib
import json
from pathlib import Path
import sqlite3

from .pose_review_geometry import canonical,polygon_value
from .mask_pose_dependency import current_pose_source

SCHEMA='assistant_visual_preannotation_v1'
FALSE_FLAGS=('human_edited','human_mask_confirmed','human_pose_confirmed','ground_truth_eligible',
    'automatic_training_eligible','robot_command_eligible','production_saved','counts_as_completed_annotation',
    'accepted_candidate','propagation_seed_eligible')


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


def validate_preannotation(proposal,formal_sha=None,image_sha=None):
    p=proposal;s=p['source'];key=p['target_key'];proof=p['preannotation'];reference=p['draft_source']
    if (p.get('schema')!=SCHEMA or p.get('origin')!='assistant_visual_preannotation' or 'template' in p or
            any(p.get(f) is not False for f in FALSE_FLAGS) or key!=s['target_key'] or
            p.get('status')!='assistant_preannotated_draft_pending_human_review' or
            reference.get('target_key')!=key or reference.get('origin')!='assistant_visual_preannotation' or
            reference.get('snapshot_revision')!=p['target_expected_revision'] or
            reference.get('current_payload_sha256')!=p['target_snapshot_payload_sha256'] or
            type(p['target_expected_revision']) is not int or p['target_expected_revision']<0 or
            (p['target_expected_revision']==0)!=(p['target_snapshot_payload_sha256'] is None) or
            p['vertex_count']!=len(p['polygon']) or proof.get('polygon_sha256')!=sha(p['polygon']) or
            proof.get('method')!='assistant_direct_native_image_contour_not_template_transfer' or
            proof.get('crop_inspected') is not True or proof.get('full_image_inspected') is not True or
            proof.get('human_saved') is not False or not proof.get('note_zh')):
        raise ValueError('Invalid assistant preannotation; no human save/template/coverage claim is allowed')
    if formal_sha is not None and p['formal_manifest_sha256']!=formal_sha:raise ValueError('Foreign preannotation formal binding')
    if image_sha is not None and proof['image_sha256']!=image_sha:raise ValueError('Preannotation native image changed')
    polygon_value(p['polygon'],*s['size'])
    box=s['bbox'];x,y,w,h=(box[f] for f in ('x','y','width','height'))
    original=[[x,y],[x+w,y],[x+w,y+h],[x,y+h]]
    import numpy as np
    if len(p['polygon'])==4 and np.allclose(sorted(p['polygon']),sorted(original),rtol=0,atol=1e-5):
        raise ValueError('The original rectangle is not a completed assistant contour draft')
    return reference


def current_preannotation_target(path,formal_sha,reference):
    """Revoke unsaved tasks when the protected pose source changes, including first saves."""
    if reference.get('snapshot_revision',-1)>0:return current_pose_source(path,formal_sha,reference)
    if reference.get('snapshot_revision')!=0 or reference.get('current_payload_sha256') is not None:return False
    path=Path(path).resolve();wal=Path(str(path)+'-wal');journal=Path(str(path)+'-journal')
    def persisted():return tuple((p.stat().st_ino,p.stat().st_size,p.stat().st_mtime_ns) if p.exists() else None for p in (path,wal,journal))
    before=persisted()
    if not path.is_file() or journal.exists() and journal.stat().st_size:return False
    if wal.exists() and not Path(str(path)+'-shm').exists():return False
    try:
        with closing(sqlite3.connect(path.as_uri()+'?mode=ro'+('' if wal.exists() else '&immutable=1'),uri=True,timeout=1)) as db:
            db.execute('PRAGMA query_only=ON');db.execute('BEGIN')
            binding=db.execute("SELECT value FROM metadata WHERE key='binding'").fetchone()
            if not binding or json.loads(binding[0])['formal_manifest_sha256']!=formal_sha:return False
            key=reference['target_key']
            if db.execute('SELECT 1 FROM annotations WHERE target_key=?',(key,)).fetchone():return False
            if db.execute('SELECT 1 FROM events WHERE target_key=? LIMIT 1',(key,)).fetchone():return False
        return before==persisted()
    except (OSError,ValueError,TypeError,KeyError,sqlite3.Error):return False
