"""Read-only mask proposals: exact revisions, template provenance and source binding."""
from __future__ import annotations

from contextlib import contextmanager
import hashlib
import json
import logging
from pathlib import Path
import sqlite3
import threading

from .cluster_targets import digest,load_dataset,target_key
from .pose_review_geometry import canonical,polygon_value

LOG=logging.getLogger('pallet.pose_review')
GALLERY_ORIGIN='mask_gallery_human_revision'
GALLERY_FIELDS=('gallery_review_database','gallery_review_snapshot','gallery_review_snapshot_sha256')


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


class MaskSuggestions:
    def __init__(self,config_path,dataset):
        self.config_path=Path(config_path);self.dataset=Path(dataset)
        self.root=Path(__file__).resolve().parents[1]
        self.lock=threading.Lock();self.fingerprint=None;self.values={}
        self.manifest_sha256=digest(self.dataset/'manifest.json')

    def gallery_settings(self,config):
        if not any(k in config for k in GALLERY_FIELDS):return None
        settings={k:config[k] for k in GALLERY_FIELDS}
        for name in GALLERY_FIELDS[:2]:
            path=(self.root/settings[name]).resolve()
            if not path.is_relative_to(self.root/'outputs'):
                raise ValueError('Gallery review path is outside outputs')
            settings[name]=path
        return settings

    @contextmanager
    def gallery_connect(self,path,*,snapshot=False):
        # Never instantiate the writable editor store or fall back to a new DB.
        if not path.resolve().is_relative_to(self.root/'outputs'):
            raise ValueError('Gallery review path is outside outputs')
        wal=Path(str(path)+'-wal');shm=Path(str(path)+'-shm');journal=Path(str(path)+'-journal')
        def signature():
            # WAL readers update shared-memory reader slots even with mode=ro.
            # Only database/WAL/journal changes indicate changed persisted data.
            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=signature()
        if journal.exists() and journal.stat().st_size:
            raise ValueError('Gallery database has an unresolved rollback journal')
        if not snapshot and wal.exists() and not shm.exists():
            raise ValueError('Live gallery WAL has no read-only shared-memory index')
        # Opening a checkpointed WAL database with mode=ro alone creates -wal
        # and -shm files. Immutable reads are safe only with no WAL, checked
        # again after the read; never use immutable as a fallback on SQL errors.
        immutable=snapshot or not wal.exists()
        db=sqlite3.connect(path.as_uri()+'?mode=ro'+('&immutable=1' if immutable else ''),
                           uri=True,timeout=1)
        try:
            db.execute('PRAGMA query_only=ON')
            binding=db.execute("SELECT value FROM metadata WHERE key='formal_manifest_sha256'").fetchone()
            if binding!=(self.manifest_sha256,):
                raise ValueError('Gallery review database belongs to another formal dataset')
            yield db
            if not snapshot and before!=signature():
                raise ValueError('Live gallery database changed during provenance check')
        finally:db.close()

    def gallery_snapshot(self,settings):
        path=settings['gallery_review_snapshot']
        if not path.resolve().is_relative_to(self.root/'outputs'):
            raise ValueError('Gallery review snapshot is outside outputs')
        # A frozen snapshot is a standalone SQLite backup, not a live WAL DB.
        if (digest(path)!=settings['gallery_review_snapshot_sha256'] or
            any(Path(str(path)+suffix).exists() and Path(str(path)+suffix).stat().st_size
                for suffix in ('-wal','-journal'))):
            raise ValueError('Gallery review snapshot changed or is not frozen')
        return path

    def gallery_template(self,p,settings):
        t=p['template'];g=t['gallery_review'];key=t['target_key']
        if any(p[name] is not False for name in ('human_mask_confirmed','human_pose_confirmed',
                'automatic_training_eligible','robot_command_eligible','production_saved') if name in p):
            raise ValueError('Gallery proposal makes unsupported human or production claims')
        if (t['origin']!=GALLERY_ORIGIN or t.get('auxiliary_seed') or g['target_key']!=key or
            type(g['revision']) is not int or g['revision']<1 or
            type(t['human_polygon_revision']) is not int or t['human_polygon_revision']!=g['revision'] or
            t['human_event_sha256']!=g['payload_sha256'] or
            t['template_human_confirmed'] is not False or
            g['snapshot_sha256']!=settings['gallery_review_snapshot_sha256'] or
            type(t['snapshot_revision']) is not int or t['snapshot_revision']<0 or
            (t['current_payload_sha256'] is None)!=(t['snapshot_revision']==0)):
            raise ValueError('Invalid gallery template origin or human claims')
        with self.gallery_connect(self.gallery_snapshot(settings),snapshot=True) as db:
            row=db.execute('SELECT revision,payload FROM reviews WHERE target_key=?',(key,)).fetchone()
            event=db.execute('SELECT revision,payload FROM events WHERE target_key=? ORDER BY revision DESC LIMIT 1',(key,)).fetchone()
        if not row or not event or row[0]!=g['revision'] or event[0]!=g['revision']:
            raise ValueError('Missing or inconsistent gallery snapshot event')
        value=json.loads(row[1]);source=value['source']
        if (payload_hash(value)!=g['payload_sha256'] or payload_hash(json.loads(event[1]))!=g['payload_sha256'] or
            value['target_key']!=key or value['revision']!=g['revision'] or
            value['event_kind']!='human_mask_gallery_revision' or value['human_edited'] is not True or
            value['status']!='human_edited_draft_pending_confirmation' or
            any(value[name] is not False for name in ('human_mask_confirmed','human_pose_confirmed',
                'automatic_training_eligible','robot_command_eligible','pose_store_written','original_proposal_modified')) or
            value['pose'] is not None):
            raise ValueError('Invalid gallery payload/event or human claims')
        if (payload_hash(source)!=g['source_binding'] or value['source_binding']!=g['source_binding'] or
            payload_hash(value['polygon'])!=g['polygon_sha256'] or
            len(value['polygon'])!=value['vertex_count'] or value['vertex_count']!=t['vertex_count']):
            raise ValueError('Gallery source binding or polygon differs')
        annotations,sources=load_dataset(self.dataset)
        frame=sources[source['frame_id']]
        annotation=next(a for a in annotations if a['frame_id']==source['frame_id'])
        index=source['box_index']
        if type(index) is not int or not 0<=index<len(annotation['boxes']):
            raise ValueError('Invalid gallery source box identity')
        expected=dict(target_key=target_key(frame['frame_id'],index),frame_id=frame['frame_id'],
            split=frame['split'],box_index=index,bbox=annotation['boxes'][index],size=frame['size'],
            source_pcd_sha256=frame['source_anchor_hash'],formal_manifest_sha256=self.manifest_sha256,
            image_sha256=digest(self.dataset/frame['image']))
        if source!=expected or source['target_key']!=key or source['split']!=t['split']:
            raise ValueError('Gallery source identity differs from the formal dataset')
        polygon_value(value['polygon'],*source['size'])
        return dict(source,policy_id=frame['sensor_policy']['policy_id'])

    def gallery_allowed(self,p,key):
        settings=p.get('_gallery_settings')
        if settings is None:return True
        self.gallery_snapshot(settings)
        # A fresh read transaction on every get observes committed WAL changes.
        with self.gallery_connect(settings['gallery_review_database']) as db:
            db.execute('BEGIN')
            if (db.execute('SELECT 1 FROM reviews WHERE target_key=?',(key,)).fetchone() or
                db.execute('SELECT 1 FROM events WHERE target_key=? LIMIT 1',(key,)).fetchone()):
                return False
            g=p['template'].get('gallery_review')
            if g:
                row=db.execute('SELECT revision,payload FROM reviews WHERE target_key=?',(g['target_key'],)).fetchone()
                event=db.execute('SELECT revision,payload FROM events WHERE target_key=? ORDER BY revision DESC LIMIT 1',
                                 (g['target_key'],)).fetchone()
                for record in (row,event):
                    if not record or record[0]!=g['revision'] or payload_hash(json.loads(record[1]))!=g['payload_sha256']:
                        return False
        return True

    def load(self):
        if not self.config_path.exists():return {}
        stat=self.config_path.stat();fingerprint=(stat.st_mtime_ns,stat.st_size)
        with self.lock:
            if fingerprint==self.fingerprint:return self.values
            try:
                config=json.loads(self.config_path.read_text())
                gallery=self.gallery_settings(config)
                if gallery:
                    with self.gallery_connect(self.gallery_snapshot(gallery),snapshot=True):pass
                path=(self.root/config['proposals']).resolve()
                if not path.is_relative_to(self.root/'outputs'):
                    raise ValueError('Mask proposal path is outside outputs')
                if config['formal_manifest_sha256']!=self.manifest_sha256:
                    self.values={};self.fingerprint=fingerprint
                    return self.values
                if digest(path)!=config['proposals_sha256']:
                    raise ValueError('Mask proposal hashes changed')
                values={}
                seed_sources={}
                gallery_templates={}
                for line in path.read_text().splitlines():
                    p=json.loads(line);key=p['target_key'];source=p['source'];t=p['template']
                    if key in values or p['formal_manifest_sha256']!=self.manifest_sha256:
                        raise ValueError('Duplicate or foreign mask proposal')
                    if p['class_id']!=t['class_id'] or source['split']!=t['split']:
                        raise ValueError('Cross-class or cross-split mask transfer')
                    if len(p['polygon'])!=p['vertex_count'] or p['vertex_count']!=t['vertex_count'] or p['vertex_count']<=4:
                        raise ValueError('Mask vertex count does not match its template')
                    polygon_value(p['polygon'],*source['size'])
                    gallery_source=None
                    if t.get('origin')==GALLERY_ORIGIN or 'gallery_review' in t:
                        if gallery is None:raise ValueError('Gallery template requires explicit review protection')
                        template_hash=payload_hash(t)
                        if template_hash not in gallery_templates:
                            gallery_templates[template_hash]=self.gallery_template(p,gallery)
                        gallery_source=gallery_templates[template_hash]
                    if t.get('auxiliary_seed'):
                        auxiliary=t['auxiliary_seed'];approved=auxiliary['config']
                        seed_config=(self.root/config['auxiliary_seed_config']).resolve()
                        if not seed_config.is_relative_to(self.root/'configs') or digest(seed_config)!=config['auxiliary_seed_config_sha256']:
                            raise ValueError('Auxiliary seed authorization hash/path changed')
                        if json.loads(seed_config.read_text())!=approved or auxiliary['config_sha256']!=hashlib.sha256(canonical(approved)).hexdigest():
                            raise ValueError('Auxiliary seed is not explicitly approved')
                        seed_path=(self.root/approved['source_proposals']).resolve()
                        if not seed_path.is_relative_to(self.root/'outputs') or digest(seed_path)!=approved['source_proposals_sha256']:
                            raise ValueError('Approved auxiliary source changed')
                        cache_key=str(seed_path)
                        if cache_key not in seed_sources:
                            seed_sources[cache_key]={s['target_key']:s for s in map(json.loads,seed_path.read_text().splitlines())}
                        seed=seed_sources[cache_key][approved['target_key']]
                        if approved['target_key']!=t['target_key'] or seed['target_key']==key:
                            raise ValueError('Auxiliary self-transfer or wrong seed identity')
                        if (hashlib.sha256(canonical(seed)).hexdigest()!=approved['source_proposal_sha256'] or
                            hashlib.sha256(canonical(seed['polygon'])).hexdigest()!=approved['polygon_sha256'] or
                            auxiliary['source_proposal_sha256']!=approved['source_proposal_sha256'] or
                            auxiliary['polygon_sha256']!=approved['polygon_sha256']):
                            raise ValueError('Auxiliary correction evidence hash differs')
                        if (auxiliary['auxiliary_hops']!=1 or approved['maximum_auxiliary_hops']!=1 or
                            approved['allow_generated_candidates_as_new_seeds'] is not False or
                            seed['template'].get('auxiliary_seed') or not seed.get('boundary_correction') or
                            seed['boundary_correction']['after']['state']!='passed'):
                            raise ValueError('Recursive or uncorrected auxiliary seed rejected')
                        if (seed['class_id']!=p['class_id'] or len(seed['polygon'])!=p['vertex_count'] or
                            any(seed['source'][k]!=source[k] for k in ('split','policy_id')) or
                            seed['source']['frame_id']==source['frame_id'] or
                            t['current_payload_sha256']!=seed['target_snapshot_payload_sha256'] or
                            t['snapshot_revision']!=seed['target_expected_revision']):
                            raise ValueError('Auxiliary seed source binding differs')
                        expected=[dict(target_key=seed['template']['target_key'],payload_sha256=seed['template']['current_payload_sha256'])]
                        if auxiliary['dependencies']!=expected or t['template_human_confirmed'] is not False or t['human_polygon_revision'] is not None:
                            raise ValueError('Auxiliary dependency or human-truth claim differs')
                    p['proposal_id']=hashlib.sha256(canonical(p)).hexdigest()
                    p['_gallery_settings']=gallery
                    p['_gallery_source']=gallery_source
                    p['version']=config['version'];values[key]=p
                if len(values)!=config['count']:raise ValueError('Unexpected mask proposal count')
                self.values=values;self.fingerprint=fingerprint
            except (ValueError,KeyError,OSError,TypeError,IndexError,StopIteration,sqlite3.Error):
                LOG.exception('Refusing invalid mask proposal sidecar')
                # Never fall back to a previously accepted but now revoked file.
                self.values={};self.fingerprint=None
            return self.values

    def get(self,key,review,row,store):
        p=self.load().get(key)
        if p is None:return None
        try:
            if not self.gallery_allowed(p,key):return None
        except (ValueError,KeyError,OSError,TypeError,sqlite3.Error):
            LOG.exception('Refusing unavailable or changed gallery review provenance')
            return None
        if review and (review.get('state') in ('deleted','deferred') or review.get('human_mask_confirmed') or review.get('human_pose_confirmed')):
            return None
        if (review['revision'] if review else 0)!=p['target_expected_revision']:
            return None
        actual=hashlib.sha256(canonical(review)).hexdigest() if review else None
        if actual!=p['target_snapshot_payload_sha256']:return None
        if any(p['source'][k]!=row[k] for k in ('target_key','frame_id','split','group_id','bbox','source_pcd_sha256','policy_id','size')):
            return None
        template=store.get(p['template']['target_key'])
        t=p['template']
        if template and template.get('state') in ('deleted','deferred'):
            return None
        if not template and not (p.get('_gallery_source') and t['current_payload_sha256'] is None and t['snapshot_revision']==0):
            return None
        if (payload_hash(template) if template else None)!=t['current_payload_sha256']:
            return None
        if 'snapshot_revision' in t and (template['revision'] if template else 0)!=t['snapshot_revision']:
            return None
        ts=p.get('_gallery_source') or template['source']
        if template and p.get('_gallery_source') and any(template['source'][k]!=ts[k] for k in
                ('target_key','frame_id','split','box_index','bbox','size','source_pcd_sha256','policy_id')):
            return None
        if ts['frame_id']==row['frame_id'] or any(ts[k]!=row[k] for k in ('split','policy_id')):
            return None
        for dependency in p['template'].get('auxiliary_seed',{}).get('dependencies',[]):
            upstream=store.get(dependency['target_key'])
            if not upstream or upstream.get('state') in ('deleted','deferred') or hashlib.sha256(canonical(upstream)).hexdigest()!=dependency['payload_sha256']:
                return None
        return {name:p[name] for name in ('proposal_id','version','polygon','vertex_count','class_id','template',
            'metrics','mask_semantics','flags','snapshot_sha256','target_expected_revision','target_snapshot_payload_sha256')}
