import json
from pathlib import Path

import numpy as np
import pytest
import torch

from pallet.pose_evaluation import box_iou,make_bundle,oracle_summary,selected_detection
from pallet.pose_inference import PalletPosePredictor,bundle_path,partial_document
from pallet.pose_model import GLOBAL_DIM,TASKS,PointNetResidual,RidgeResidual,base_prediction


def cfg():
    return {'points':64,'geometry_points':256,'ransac_iterations':32,'plane_threshold':.005,
        'unverified_unit_policy':'assume_native_numeric_metres_research_only'}


def arrays():
    yy,xx=np.mgrid[:16,:16]
    points=np.stack((xx*0+2,(xx-7.5)/20,(yy-7.5)/40,xx*0+1),axis=-1).reshape(-1,4).astype(np.float32)
    return points,np.arange(256,dtype=np.int32).reshape(16,16)


def fake_predictor():
    predictor=PalletPosePredictor.__new__(PalletPosePredictor)
    predictor.spec={'pose_features':cfg(),'selected_planar_family':'geometry'}
    predictor.allow_unverified_units=False
    predictor.device=torch.device('cpu')
    predictor.detect=lambda image:[{'box_xywh':[0,0,16,16],'confidence':.9}]
    return predictor


def test_partial_prediction_never_fabricates_missing_rotation_or_z():
    plane=partial_document([2,.1,1,0],TASKS[0])
    assert plane['z'] is None and plane['quaternion'] is None and plane['normal'] is None
    assert plane['theta_degrees']==0 and not plane['robot_command_eligible']
    normal=partial_document([2,.1,.2,1,0,0],TASKS[1])
    assert normal['theta_degrees'] is None and normal['yaw'] is None and normal['roll'] is None
    assert normal['normal']==[1,0,0] and not normal['full_six_dof']


def test_real_roi_prediction_needs_no_ground_truth_and_rejects_implicit_units():
    predictor=fake_predictor();points,mapping=arrays()
    with pytest.raises(ValueError,match='units unverified'):
        predictor.pose(points,mapping,[0,0,16,16],16,16)
    result=predictor.predict(np.zeros((16,16),dtype=np.uint8),points,mapping,scale_to_m=1.)
    assert result['detections'][0]['pose']['x']==pytest.approx(2)
    assert result['ground_truth_used_for_inference'] is False
    assert not result['robot_command_eligible']
    bad=predictor.predict(np.zeros((16,16),dtype=np.uint8),points,mapping)
    assert bad['detections'][0]['pose'] is None and bad['detections'][0]['error']
    with pytest.raises(ValueError,match='registration'):
        predictor.predict(np.zeros((32,16),dtype=np.uint8),points,mapping,scale_to_m=1.)


def test_detector_matching_is_scoring_only_and_orders_by_confidence():
    truth=[0,0,10,10]
    detections=[{'box_xywh':[50,50,10,10],'confidence':.99},
        {'box_xywh':truth,'confidence':.6},{'box_xywh':truth,'confidence':.8}]
    assert selected_detection(detections,truth,.5)==2
    assert selected_detection(detections[:1],truth,.5) is None
    assert box_iou(truth,truth)==1 and box_iou(truth,detections[0]['box_xywh'])==0


def test_failed_oracle_inputs_remain_in_the_success_denominator():
    y=np.array([[1.,0,1.,0],[1.,0,1.,0]])
    prediction=y.copy();prediction[1]=np.nan
    result=oracle_summary(prediction,y,[{'group_id':'a'},{'group_id':'b'}])
    assert result['attempted_samples']==2 and result['input_failures']==1
    assert result['overall']['success_50mm_5deg']==1.
    assert result['success_rate_all_samples_50mm_5deg']==.5


def test_bundle_paths_cannot_escape(tmp_path):
    assert bundle_path(tmp_path,'model.pt')==tmp_path/'model.pt'
    with pytest.raises(ValueError):bundle_path(tmp_path,'../escape.pt')
    with pytest.raises(ValueError):bundle_path(tmp_path,'/absolute.pt')


def test_portable_pointnet_weights_are_tensor_only_and_match_frozen_source(tmp_path):
    from pallet.pose_inference import digest_file
    out=tmp_path/'run';out.mkdir()
    detector=out/'detector.pt';detector.write_bytes(b'isolated dummy detector')
    weights={}
    for key,task in (('pointnet',TASKS[0]),('normal_pointnet',TASKS[1])):
        p=out/(key+'.pt');model=PointNetResidual(task)
        torch.save({'task':task,'model':model.state_dict(),'optimizer':None},p)
        weights[key]={'path':str(p),'sha256':digest_file(p)}
    g=np.zeros((3,GLOBAL_DIM));g[:,0]=[1,2,3];g[:,6]=1
    ridge=RidgeResidual().fit(g,base_prediction(g,TASKS[0]));p=out/'ridge.json'
    p.write_text(json.dumps(ridge.document()));weights['ridge']={'path':str(p),'sha256':digest_file(p)}
    plan={'weights':weights,'selected_planar_family':'pointnet'}
    config={'pose':cfg(),'detector':{'imgsz':640,'conf':.25,'max_det':30}}
    bundle=make_bundle(out,config,plan,{'best':str(detector),'best_sha256':digest_file(detector)})
    spec=json.loads((bundle/'inference_config.json').read_text())
    for task,path in spec['pointnet_weights'].items():
        state=torch.load(bundle/path,map_location='cpu',weights_only=True)
        assert set(state)=={'task','model'} and state['task']==task
    make_bundle(out,config,plan,{'best':str(detector),'best_sha256':digest_file(detector)})
