"""User-authorized persistent retirement policy for future data operations."""
from functools import lru_cache
import hashlib
import json
from pathlib import Path


CONTROL = Path(__file__).resolve().parents[2] / 'configs/active_dataset.json'


@lru_cache(maxsize=8)
def _load(path, mtime_ns, size):
    control = json.loads(Path(path).read_text())
    policy_path = Path(control['exclusions'])
    raw = policy_path.read_bytes()
    if hashlib.sha256(raw).hexdigest() != control['exclusions_sha256']:
        raise ValueError('Active dataset exclusion policy hash mismatch')
    policy = json.loads(raw)
    if policy.get('authorized_by_user') is not True:
        raise ValueError('Retirement policy lacks user authorization')
    return control, policy


def active_policy():
    if not CONTROL.exists():
        return {}, {'frames': []}
    stat = CONTROL.stat()
    control, policy = _load(str(CONTROL), stat.st_mtime_ns, stat.st_size)
    policy_path = Path(control['exclusions'])
    policy_stat = policy_path.stat()
    _verify_payload(str(policy_path), policy_stat.st_mtime_ns, policy_stat.st_ctime_ns,
                    policy_stat.st_size, control['exclusions_sha256'])
    return control, policy


@lru_cache(maxsize=8)
def _verify_payload(path, mtime_ns, ctime_ns, size, expected):
    if hashlib.sha256(Path(path).read_bytes()).hexdigest() != expected:
        raise ValueError('Active dataset exclusion policy changed')


@lru_cache(maxsize=8)
def _indices(path, mtime_ns, ctime_ns, size):
    rows = json.loads(Path(path).read_text())['frames']
    return ({fid for row in rows for fid in [row['frame_id'], *row.get('alias_frame_ids', [])]},
            {row['source_sha256'] for row in rows},
            {path for row in rows for path in row.get('source_paths', [])})


def exclusion_ids():
    _, policy = active_policy()
    return {fid for row in policy['frames'] for fid in [row['frame_id'], *row.get('alias_frame_ids', [])]}


def is_excluded(record):
    control, policy = active_policy()
    if not policy['frames']:
        return False
    path = Path(control['exclusions'])
    stat = path.stat()
    ids, hashes, paths = _indices(str(path), stat.st_mtime_ns, stat.st_ctime_ns, stat.st_size)
    digest = getattr(record, 'source_sha256', None)
    pcd = getattr(record, 'pcd', None)
    return (record.frame_id in ids or bool(digest and digest in hashes)
            or bool(pcd and str(Path(pcd).resolve()) in paths))


def require_eligible(record):
    if is_excluded(record):
        raise ValueError(f'Frame retired by user from future training/annotation: {record.frame_id}; use the active cleaned dataset')


def eligible_records(records):
    return [record for record in records if not is_excluded(record)]


def annotation_record(frame):
    from .manifest import FrameRecord
    return FrameRecord(frame.frame_id, frame.group_id, 'annotation', {}, None,
                       frame.source_anchor_hash)


def annotation_eligible(frame):
    return not is_excluded(annotation_record(frame))


def active_protocol(fallback='outputs/protocol_v5'):
    control, _ = active_policy()
    return control.get('protocol', fallback)
