from dataclasses import replace
from pathlib import Path
import json
import numpy as np
import pytest

from pallet.data.orientation import orient_grid,rotation_degrees,rotate_rectangle,rotate_document
from pallet.data.loader import load_frame,cache_frame
from pallet.data.manifest import FrameRecord


def test_aligned_channels_and_xyz_are_reindexed_without_axis_rotation():
    grid=np.arange(24,dtype=np.float32).reshape(2,3,4)
    expected=grid[::-1,::-1,:].copy()
    result=orient_grid(grid,{'pixel_rotation_degrees':180})
    np.testing.assert_array_equal(result,expected)
    assert result.dtype==grid.dtype and result.flags['C_CONTIGUOUS']
    np.testing.assert_array_equal(orient_grid(result,{'pixel_rotation_degrees':180}),grid)


@pytest.mark.parametrize('value',[90,270,360,True,'180'])
def test_unregistered_rotation_rejected(value):
    with pytest.raises(ValueError):rotation_degrees({'pixel_rotation_degrees':value})


def test_edge_coordinate_rotation_preserves_extent_and_round_trips():
    assert rotate_rectangle([[0,0],[240,96]],240,96)==[[0,0],[240,96]]
    box=[[30,5],[65,22]]
    rotated=rotate_rectangle(box,240,96)
    assert rotated==[[175,74],[210,91]]
    assert rotate_rectangle(rotated,240,96)==box
    mask=np.zeros((96,240),bool);mask[5:22,30:65]=True
    y,x=np.where(orient_grid(mask,{'pixel_rotation_degrees':180}))
    assert [x.min(),y.min(),x.max()+1,y.max()+1]==[175,74,210,91]


def test_json_rectangles_and_ignore_regions_rotate_together_without_accepting_proposals():
    doc={'imageWidth':240,'imageHeight':96,'imageData':None,'flags':{'unreviewed':True},'shapes':[
        {'shape_type':'rectangle','label':'pallet','points':[[30,5],[65,22]]},
        {'shape_type':'rectangle','label':'__ignore__','points':[[0,0],[10,8]]}]}
    new=rotate_document(doc)
    assert new['shapes'][0]['points']==[[175,74],[210,91]]
    assert new['shapes'][1]['points']==[[230,88],[240,96]]
    assert doc['shapes'][0]['points']==[[30,5],[65,22]] and new['flags']==doc['flags']


def test_cached_and_uncached_sensor_routes_rotate_exactly_once(tmp_path):
    path=tmp_path/'frame.pcd'
    header='VERSION .7\nFIELDS x y z intensity\nSIZE 4 4 4 4\nTYPE F F F F\nCOUNT 1 1 1 1\nWIDTH 3\nHEIGHT 2\nPOINTS 6\nDATA ascii\n'
    table=np.array([[d,0,0,i] for d,i in zip(range(1,7),range(11,17))],np.float32)
    path.write_text(header+'\n'.join(' '.join(map(str,row)) for row in table)+'\n')
    policy={'grid':[2,3],'depth_available':True,'depth_source':'pcd','depth_axis':0,'scale_to_mm':1}
    native=FrameRecord('orientation-test','g','native',{'pcd':path},policy,'test-source')
    upright=replace(native,sensor_config={**policy,'pixel_rotation_degrees':180})
    raw=load_frame(native);expected=raw[::-1,::-1,:]
    uncached=load_frame(upright)
    np.testing.assert_array_equal(uncached,expected)
    cached=cache_frame(upright,tmp_path/'upright.npz')
    np.testing.assert_array_equal(load_frame(cached),expected)
    # Rebinding an upside-down/native cache to a corrected policy must be rejected.
    old_cache=cache_frame(native,tmp_path/'native.npz')
    with pytest.raises(ValueError,match='frozen source/policy'):
        load_frame(replace(old_cache,sensor_config=upright.sensor_config))
