"""Reuse full source verification only while every source generation is unchanged.

Every request probes the inventory, filesystem identity/ctime/mtime and persistent
read-only SQLite data_version connections. No TTL permits a known change through.
Only full hash/logical-row verification can establish a new trusted generation.
"""
from pathlib import Path
import sqlite3
import threading
import time

from .cluster_targets import digest
from .mask_model_training_data import PROJECT, read, require
from .mask_quality_recovery import fingerprint, POSE
from .mask_taxonomy_data import ROOT, REQUESTS, REVIEWS


def database_inventory():
    return {str(p.relative_to(PROJECT)) for p in (PROJECT/'outputs').glob('pallet_mask*_reviews_v*/mask_reviews.sqlite3') if p.parent != REVIEWS}


def worklist_inventory():
    # Membership discovery only: source consistency does not need parsing the
    # 136MB of JSONL just to collect target membership into an empty dictionary.
    return {str(p.relative_to(PROJECT)) for pattern in ('requests.jsonl','proposals.jsonl','tasks.jsonl','inspection_targets.jsonl')
        for p in (PROJECT/'outputs').glob('pallet_mask*/'+pattern)
        if p.parent not in (ROOT,REQUESTS) and (p.parent/'manifest.json').exists()}


class SourceGuard:
    def __init__(self, *, project, databases, files, inventories, discover_databases,
                 discover_inventories, extra_databases=(), pinned_files=None):
        self.project=Path(project).resolve();self.databases=dict(databases);self.files=dict(files)
        self.inventories=dict(inventories);self.pinned_files=dict(pinned_files or {})
        self.discover_databases=discover_databases;self.discover_inventories=discover_inventories
        self.expected_databases=set(self.databases)-set(extra_databases)
        self.expected_files={}
        for mapping in (self.files,self.inventories,self.pinned_files):
            for name,h in mapping.items():
                require(name not in self.expected_files or self.expected_files[name]==h,'Conflicting frozen source hashes')
                self.expected_files[name]=h
        for name in self.expected_files.keys()|self.databases.keys():
            require((self.project/name).resolve().is_relative_to(self.project),'Source outside bound project')
        self.lock=threading.RLock();self.connections={};self.verified_token=None;self.valid=False;self.closed=False
        self.probes=0;self.full_checks=0;self.full_seconds=0.;self.last_error=None

    @classmethod
    def for_gallery(cls, manifest_sha256):
        manifest=read(REQUESTS/'manifest.json');dataset=read(ROOT/'dataset_manifest.json')
        require(digest(REQUESTS/'manifest.json')==manifest_sha256 and digest(ROOT/'dataset_manifest.json')==manifest['training_dataset_manifest_sha256'],'Source guard dataset/task binding differs')
        require(digest(ROOT/'source_binding.json')==manifest['source_binding_sha256'] and digest(ROOT/'private/protection.json')==dataset['files']['private/protection.json'],'Frozen source guard inventory changed')
        binding=read(ROOT/'source_binding.json');protection=read(ROOT/'private/protection.json')
        pinned={str(p.relative_to(PROJECT)):h for p,h in (
            (REQUESTS/'manifest.json',manifest_sha256),
            (ROOT/'dataset_manifest.json',manifest['training_dataset_manifest_sha256']),
            (ROOT/'source_binding.json',manifest['source_binding_sha256']),
            (ROOT/'private/protection.json',dataset['files']['private/protection.json']))}
        return cls(project=PROJECT,databases=binding['database_fingerprints'],files=binding['file_hashes'],
            inventories=protection['inventories'],discover_databases=database_inventory,
            discover_inventories=worklist_inventory,extra_databases=[str(POSE.relative_to(PROJECT))],pinned_files=pinned)

    @staticmethod
    def stamp(path):
        try:
            s=path.stat()
            return s.st_dev,s.st_ino,s.st_mode,s.st_size,s.st_mtime_ns,s.st_ctime_ns
        except FileNotFoundError:return None

    def _token(self):
        self.probes+=1
        discovered_db=frozenset(self.discover_databases());discovered_inv=frozenset(self.discover_inventories())
        files=tuple((name,self.stamp(self.project/name)) for name in sorted(self.expected_files))
        databases=[]
        for name in sorted(self.databases):
            path=self.project/name;stamp=self.stamp(path);wal_stamp=self.stamp(Path(str(path)+'-wal'))
            # SQLite can fchmod an existing WAL on a read-only connection open,
            # changing ctime without changing any data. Logical commits are
            # caught by the persistent connection's data_version; also watch
            # WAL identity, permissions, length and content-write mtime.
            wal=wal_stamp[:5] if wal_stamp is not None else None
            if stamp is None:raise OSError('Source database missing')
            identity=stamp[:2];previous=self.connections.get(name)
            if previous is None or previous[0]!=identity:
                if previous:previous[1].close()
                db=sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True,check_same_thread=False,isolation_level=None,timeout=.1)
                db.execute('PRAGMA query_only=ON');self.connections[name]=(identity,db)
            else:db=previous[1]
            version=db.execute('PRAGMA data_version').fetchone()[0]
            databases.append((name,stamp,wal,version))
        return discovered_db,discovered_inv,files,tuple(databases)

    def _full_check(self):
        self.full_checks+=1;start=time.perf_counter()
        try:
            if set(self.discover_databases())!=self.expected_databases or set(self.discover_inventories())!=set(self.inventories):return False
            # Inventory hashes already occur among the frozen files: hash once,
            # and never decode JSONL when no membership lookup is needed.
            if not all(digest(self.project/name)==expected for name,expected in self.expected_files.items()):return False
            return all(fingerprint(self.project/name)==expected for name,expected in self.databases.items())
        finally:self.full_seconds+=time.perf_counter()-start

    def current(self):
        with self.lock:
            if self.closed:return False
            try:
                for _ in range(2):
                    before=self._token()
                    if before==self.verified_token:return self.valid
                    self.valid=False
                    valid=self._full_check();after=self._token()
                    if before==after:
                        self.verified_token=after;self.valid=valid;self.last_error=None
                        return valid
                self.verified_token=None;self.last_error='sources_changed_during_verification'
            except (OSError,sqlite3.Error,ValueError,KeyError,TypeError):
                self.verified_token=None;self.valid=False;self.last_error='source_probe_or_verification_failed'
            return False

    def stats(self):
        with self.lock:return dict(probes=self.probes,full_checks=self.full_checks,full_seconds=self.full_seconds,valid=self.valid,last_error=self.last_error)

    def close(self):
        with self.lock:
            for _,db in self.connections.values():db.close()
            self.connections.clear();self.valid=False;self.closed=True
