import json

import numpy as np
import pytest
import torch

from pallet.pose_model import (GLOBAL_DIM, POINT_DIM, TASKS, PointNetResidual,
    RidgeResidual, angular_error_degrees, base_prediction, canonical_normal,
    group_folds, grouped_metrics, partial_loss, pose_metrics, roi_features,
    target_array)
from pallet.pose_training import load_net, predict_net, train_net


def config():
    return {'points':64,'geometry_points':256,'ransac_iterations':64,
        'plane_threshold':.005,'unverified_unit_policy':'assume_native_numeric_metres_research_only',
        'lr':.001,'batch':2}


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


def test_geometry_features_are_measured_ordered_and_finite_with_explicit_unit_flag():
    points,mapping=cloud();points[0,3]=np.nan
    f,g,meta=roi_features(points,mapping,[0,0,16,16],16,16,config(),scale_to_m=1.)
    assert f.shape==(64,POINT_DIM) and g.shape==(GLOBAL_DIM,)
    assert np.isfinite(f).all() and np.isfinite(g).all()
    assert meta['plane_success'] and not meta['unverified_units_research_assumption']
    assert abs(g[0]-2)<1e-6
    assert np.allclose(g[6:9],[1,0,0],atol=1e-5)
    _,_,meta=roi_features(points,mapping,[0,0,16,16],16,16,config())
    assert meta['unverified_units_research_assumption'] and meta['point_scale_to_m'] is None


@pytest.mark.parametrize('box',[[0,0,0,1],[100,100,5,5],[0,0,float('nan'),3],[-10,-10,1,1]])
def test_bad_roi_never_silently_returns_a_successful_pose(box):
    points,mapping=cloud()
    with pytest.raises(ValueError):roi_features(points,mapping,box,16,16,config(),scale_to_m=1.)


def test_missing_points_scale_and_bad_mapping_fail_closed():
    points,mapping=cloud();points[:,:3]=0
    with pytest.raises(ValueError,match='16 measured'):roi_features(points,mapping,[0,0,16,16],16,16,config())
    points,mapping=cloud();points[:,:3]*=1000
    with pytest.raises(ValueError,match='scale'):roi_features(points,mapping,[0,0,16,16],16,16,config())
    _,g,_=roi_features(points,mapping,[0,0,16,16],16,16,config(),scale_to_m=.001)
    assert g[0]==pytest.approx(2)
    mapping[0,0]=999
    with pytest.raises(ValueError,match='escapes'):roi_features(points,mapping,[0,0,16,16],16,16,config())


def test_circular_metric_wraparound_and_zero_error():
    assert angular_error_degrees(179,-179)==pytest.approx(2.)
    t=np.array([[1.,0.,1.,0.]])
    m=pose_metrics(t,t,TASKS[0]);assert m['position_mae_mm']==0 and m['angle_mae_degrees']==0
    assert m['success_50mm_5deg']==1.
    n=np.array([[1,0,0,1,0,0]],dtype=float)
    assert pose_metrics(n,n,TASKS[1])['angle_mae_degrees']==0


def test_group_folds_never_split_capture_groups_or_omit_samples():
    rows=[{'group_id':g} for g,count in (('large',40),('a',8),('b',5),('c',3),('d',2)) for _ in range(count)]
    folds=group_folds(rows,3,42)
    seen=[]
    for ti,vi in folds:
        assert not set(ti)&set(vi)
        assert not {rows[i]['group_id'] for i in ti}&{rows[i]['group_id'] for i in vi}
        seen+=vi
    assert sorted(seen)==list(range(len(rows)))
    assert folds==group_folds(rows,3,42)
    with pytest.raises(ValueError):group_folds([{'group_id':'one'}]*38,3)


def test_only_declared_pose_components_become_targets():
    row={'subset':'overlap','pose':{'kind':TASKS[0],'issues':[],
        'values':{'x_gt':2.,'y_gt':.1,'theta_d_gt':179.,'z_gt':None},
        'supervision_mask':{'x_gt':True,'y_gt':True,'theta_d_gt':True,'z_gt':False}}}
    y=target_array(row,TASKS[0]);assert len(y)==4 and np.isfinite(y).all()
    row['pose']['supervision_mask']['x_gt']=False
    with pytest.raises(ValueError):target_array(row,TASKS[0])
    row['pose']['supervision_mask']['x_gt']=True;row['subset']='archive_only'
    with pytest.raises(ValueError):target_array(row,TASKS[0])


def test_ridge_standardization_fits_training_only_and_roundtrips():
    x=np.zeros((8,GLOBAL_DIM));x[:,0]=np.arange(8)/10+1;x[:,6]=1
    y=base_prediction(x,TASKS[0]);y[:,0]+=.02
    model=RidgeResidual(alpha=1).fit(x,y)
    assert np.allclose(model.mean,x.mean(axis=0))
    before=model.mean.copy();model.predict(x*100)
    assert np.array_equal(model.mean,before)
    restored=RidgeResidual.from_document(json.loads(json.dumps(model.document())))
    assert np.allclose(restored.predict(x),model.predict(x))
    assert np.isfinite(model.predict(x)).all()


@pytest.mark.parametrize('task',TASKS)
def test_pointnet_is_permutation_invariant_and_starts_at_geometric_baseline(task):
    torch.set_num_threads(1);torch.manual_seed(4)
    model=PointNetResidual(task).eval()
    points=torch.randn(2,64,POINT_DIM)
    g=torch.zeros(2,GLOBAL_DIM);g[:,0]=2.;g[:,6]=1.
    with torch.no_grad():
        a=model(points,g);b=model(points[:,torch.randperm(64)],g)
    assert torch.allclose(a,b,atol=1e-6)
    assert np.allclose(a.numpy(),base_prediction(g.numpy(),task))
    assert torch.isfinite(partial_loss(a,a,task))


def test_small_real_optimizer_run_checkpoint_and_no_validation_invention(tmp_path):
    torch.set_num_threads(1)
    p,m=cloud();f,g,meta=roi_features(p,m,[0,0,16,16],16,16,config(),scale_to_m=1.)
    items=[{'row':{'sample_id':str(i),'group_id':'one'},'features':f[None],
        'globals':g[None],'target':np.array([2.02,.01,1.,0.],dtype=np.float32)} for i in range(3)]
    model,result=train_net(items,[],TASKS[0],config(),tmp_path/'run','cpu',42,2)
    assert result['epochs_completed']==2 and result['selection_samples']==0
    assert result['selection']=='fixed_epoch_refit_no_heldout_selection'
    loaded,_=load_net(result['checkpoint'])
    assert np.allclose(predict_net(loaded,items,'cpu'),predict_net(model,items,'cpu'))
    _,same=train_net(items,[],TASKS[0],config(),tmp_path/'run','cpu',42,2)
    assert same==result
    with pytest.raises(ValueError,match='groups overlap'):
        train_net(items[:2],items[2:],TASKS[0],config(),tmp_path/'bad','cpu',42,2)


def test_macro_group_metrics_do_not_let_large_capture_group_dominate_selection():
    target=np.tile([1.,0.,1.,0.],(11,1));prediction=target.copy();prediction[-1,0]+=.1
    rows=[{'group_id':'large'}]*10+[{'group_id':'small'}]
    result=grouped_metrics(prediction,target,rows,TASKS[0])
    assert result['overall']['macro_group_selection_score']>result['overall']['selection_score']


def test_normal_sign_canonicalization_does_not_invent_roll_about_normal():
    assert np.allclose(canonical_normal([-1,0,0]),[1,0,0])
    with pytest.raises(ValueError):canonical_normal([0,0,0])
