import hashlib
import json
from pathlib import Path

import pytest

from pallet.data import eligibility
from pallet.data.loader import load_frame, NormalizationStats
from pallet.data.manifest import FrameRecord
from pallet.experiments.dataset import PalletDataset
from pallet.annotation import AnnotationSet, Box, FrameAnnotation
from pallet.clean_intensity_review import safe_bytes, proposal_document


@pytest.fixture
def retired_policy(tmp_path, monkeypatch):
    policy = tmp_path/'exclusions.json'
    policy.write_text(json.dumps({'authorized_by_user':True,'frames':[
        {'frame_id':'black','alias_frame_ids':['black-copy'],'source_sha256':'bad-hash',
         'source_paths':[str(tmp_path/'retired.pcd')]}]}))
    control=tmp_path/'active.json'
    control.write_text(json.dumps({'exclusions':str(policy),'exclusions_sha256':hashlib.sha256(policy.read_bytes()).hexdigest(),
        'protocol':'clean-protocol'}))
    monkeypatch.setattr(eligibility,'CONTROL',control)
    return policy


@pytest.mark.parametrize('fid,digest,path', [
    ('black','other',None),('black-copy','other',None),('renamed','bad-hash',None),
    ('other','other','retired.pcd')])
def test_identity_alias_hash_and_path_cannot_reenter(retired_policy,fid,digest,path):
    record=FrameRecord(fid,'g','native',{'pcd':retired_policy.parent/path} if path else {},None,digest)
    assert eligibility.is_excluded(record)
    # Retirement must be checked before any IO or cached tensor read.
    with pytest.raises(ValueError,match='retired'):
        load_frame(record)


def test_dataset_rejects_confirmed_negative_when_retired(retired_policy):
    record=FrameRecord('black','g','native',{},None,'bad-hash')
    frame=FrameAnnotation('black','g','none',32,24,status='negative',split='train',source_anchor_hash='bad-hash')
    with pytest.raises(ValueError,match='retired'):
        PalletDataset([record],AnnotationSet([frame]),NormalizationStats(1,1),require_review=False)


def test_tampered_policy_rejected_after_first_load(retired_policy):
    assert eligibility.active_protocol()=='clean-protocol'
    retired_policy.write_text(json.dumps({'authorized_by_user':True,'frames':[]}))
    with pytest.raises(ValueError,match='policy changed'):
        eligibility.active_policy()


def test_unavailable_depth_alone_is_not_a_retirement_reason(retired_policy):
    record=FrameRecord('good-intensity','g','native',{}, {'depth_available':False},'good-hash')
    assert not eligibility.is_excluded(record)


def test_reconstruction_review_does_not_inherit_manual_truth():
    row={'size':[224,172],'image':'images/train/key.png','group_id':'g','domain':'d','source_anchor_hash':'h'}
    pred={'boxes_xyxy_score':[], 'binding':{'checkpoint_sha256':'model','threshold_sha256':'threshold'},'threshold':.7}
    doc=proposal_document('f',row,pred,{'f':{}},{'f'})
    assert doc['flags']['proposal_only'] and doc['flags']['unreviewed']
    assert not doc['flags']['human_reviewed'] and not doc['flags']['confirmed_negative']
    assert doc['pallet_prediction']['previously_manually_checked']
    assert doc['pallet_prediction']['independent_reference'] is False


def test_resume_preserves_human_modified_json(tmp_path):
    output=tmp_path/'review.json'; output.write_bytes(b'manual-edit')
    with pytest.raises(ValueError,match='Preserving modified output'):
        safe_bytes(output,b'model-proposal')
    assert output.read_bytes()==b'manual-edit'


def test_retired_annotation_cannot_be_reviewed_or_exported_for_training(retired_policy,tmp_path,monkeypatch):
    import pallet.annotation.workflow as workflow
    from pallet.annotation import Review, record_review, export_coco, export_audit, export_yolo
    frame=FrameAnnotation('black','g','image.png',32,24,status='pos',boxes=[Box(1,1,5,5)],
        split='train',source_anchor_hash='bad-hash')
    with pytest.raises(ValueError,match='retired'):
        record_review(frame,Review('r','approve'))
    monkeypatch.setattr(workflow,'reference_eligible',lambda f:True)
    labels=AnnotationSet([frame])
    assert export_coco(labels)['images']==[]
    assert export_yolo(labels,tmp_path/'yolo')==[]
    assert len(export_audit(labels)['images'])==1  # Historical audit remains available.
