import hashlib
import json
from pathlib import Path

import pytest

from pallet.pose_detector_training import stage_detector


def fake_formal(tmp_path,leak=False):
    formal=tmp_path/'formal';formal.mkdir()
    rows=[]
    for i,split in enumerate(('train','val','test')):
        files={}
        for relative,raw in ((f'images/{split}/{i}.png',b'image'),(f'labels/{split}/{i}.txt',b'0 .5 .5 .2 .2\n')):
            p=formal/relative;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(raw)
            files[relative]=hashlib.sha256(raw).hexdigest()
        rows.append({'frame_id':str(i),'group_id':'shared' if leak else str(i),'split':split,
            'source_anchor_hash':str(i),'image':f'images/{split}/{i}.png',
            'yolo_label':f'labels/{split}/{i}.txt','files':files})
    (formal/'frames.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in rows))
    (formal/'manifest.json').write_text('{}')
    return formal


def test_detector_training_view_copies_train_val_without_test_or_source_writes(tmp_path):
    formal=fake_formal(tmp_path);view=tmp_path/'view'
    rows=stage_detector(formal,view)
    assert {r['split'] for r in rows}=={'train','val'}
    assert not (view/'images/test').exists() and not (view/'labels/test').exists()
    source=formal/'labels/train/0.txt';copy=view/'labels/train/0.txt'
    assert source.stat().st_ino!=copy.stat().st_ino
    copy.write_text('edit isolated view')
    assert source.read_text()=='0 .5 .5 .2 .2\n'
    with pytest.raises(ValueError):stage_detector(formal,view)


def test_detector_view_rejects_cross_split_groups_and_formal_subdirectory(tmp_path):
    formal=fake_formal(tmp_path,leak=True)
    with pytest.raises(ValueError,match='groups overlap'):stage_detector(formal,tmp_path/'view')
    with pytest.raises(ValueError,match='independent'):stage_detector(formal,formal/'view')
