from dataclasses import replace
import json

import numpy as np
from PIL import Image
import pytest

from pallet.data.manifest import FrameRecord, scan_dataset, canonical_records
from pallet.data.loader import cache_frame, load_frame
from pallet.data.sensors import build_registry, attach_registry, projection_evidence
from pallet.data.protocol import file_digest, load_protocol, write_json


def _sensor(tmp_path):
    h,w=24,32
    v,u=np.mgrid[:h,:w]
    z=np.full((h,w),2.0)
    xyz=np.stack(((u/(w-1)*2-1)*z*.5,(v/(h-1)*2-1)*z*.4,z,np.full_like(z,25)),axis=-1).astype('<f4')
    root=tmp_path/'2024_10_30';root.mkdir()
    path=root/'point_cloud_xyzi_30-10-2024_12-00-00.pcd'
    path.write_bytes((f'FIELDS x y z intensity\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH {w}\nHEIGHT {h}\nPOINTS {w*h}\nDATA binary\n').encode()+xyz.tobytes())
    Image.fromarray((z*1000).astype('uint16')).save(root/'depth_image_30-10-2024_12-00-00.png')
    return canonical_records(scan_dataset(tmp_path)),xyz


def test_paired_metric_evidence_recovers_z_axis_not_universal_x(tmp_path):
    records,points=_sensor(tmp_path)
    assert projection_evidence(points.reshape(-1,4),(24,32))['axis']==2
    registry=build_registry(records,tmp_path/'sensors.json')
    registered=attach_registry(records,registry)[0]
    assert registered.sensor_config['depth_available']
    assert registered.sensor_config['depth_axis']==2
    assert registered.sensor_config['scale_to_mm']==1000
    frame=load_frame(registered)
    np.testing.assert_allclose(frame[...,0],2000)
    assert np.all(load_frame(records[0])[...,2]==0)


def test_cached_sensor_policy_is_not_silently_reinterpreted(tmp_path):
    records,_=_sensor(tmp_path)
    record=attach_registry(records,build_registry(records,tmp_path/'s.json'))[0]
    record=replace(record,source_sha256=file_digest(record.pcd))
    cached=cache_frame(record,tmp_path/'frame.npz')
    np.testing.assert_array_equal(load_frame(cached),load_frame(record))
    changed=replace(cached,sensor_config={**record.sensor_config,'scale_to_mm':1})
    with pytest.raises(ValueError,match='frozen source/policy'):
        load_frame(changed)


def test_frozen_protocol_rejects_manifest_rewrite(tmp_path):
    folder=tmp_path/'protocol';folder.mkdir()
    write_json(folder/'splits.json',{'assignments':{}})
    (folder/'manifest.jsonl').write_text('')
    write_json(folder/'protocol.json',{'files':{name:file_digest(folder/name) for name in ['splits.json','manifest.jsonl']}})
    assert load_protocol(folder)[0]==[]
    (folder/'manifest.jsonl').write_text('{}\n')
    with pytest.raises(ValueError,match='frozen protocol file changed'):
        load_protocol(folder)
