from copy import deepcopy
import json
from pathlib import Path
import sqlite3

import numpy as np
import pytest
import torch

from pallet.pose_refinement import (NormalizedPointNet, decoded, feature_values,
    loss_value, original_targets, residual_target, ridge_fit, ridge_predict,
    score_values, validate_review, live_rows)
from pallet.pose_review_geometry import basis_for, pose_value


def candidate():
    sensor={'forward_axis':0,'up_axis':2,'forward_sign':1,'up_sign':1}
    return {'center':[2.,.1,-.2],'basis':basis_for([1,0,0],sensor).tolist(),'half_width':.5}


def example():
    rng=np.random.default_rng(2)
    xyz=np.c_[rng.normal(2,.005,300),rng.uniform(-.5,.5,300),rng.uniform(-.3,-.1,300),rng.uniform(0,100,300)]
    uv=np.c_[rng.uniform(10,100,300),rng.uniform(10,50,300)]
    box={'x':10.,'y':10.,'width':90.,'height':40.}
    return xyz,uv,box


def test_dimensionless_features_invariant_to_native_unit_scaling():
    xyz,uv,box=example();c=candidate()
    a=feature_values(xyz,uv,[120,80],box,c,42,64)
    scaled=xyz.copy();scaled[:,:3]*=1000;c2=deepcopy(c);c2['center']=(np.array(c2['center'])*1000).tolist();c2['half_width']*=1000
    b=feature_values(scaled,uv,[120,80],box,c2,42,64)
    assert np.allclose(a[0],b[0],atol=1e-5) and np.allclose(a[1],b[1],atol=1e-5)
    assert b[3]==a[3]*1000


def test_residual_encoding_decoding_and_180_direction():
    base=np.array([2.,.1,-.2]);width=1.2;direction=np.array([np.cos(.3),np.sin(.3)])
    row={'pose':{'x':2.03,'y':-.01,'theta_degrees':179.8}}
    residual=residual_target(row,base,width,direction)
    pose=decoded(residual[None],base[None],np.array([width]),direction[None])[0]
    assert np.allclose(pose[:2],[2.03,-.01],atol=1e-7)
    assert np.degrees(np.arctan2(pose[3],pose[2]))==pytest.approx(179.8,abs=1e-5)


def test_new_pointnet_initialization_and_finite_loss():
    model=NormalizedPointNet();f=torch.randn(2,64,7);g=torch.randn(2,16)
    prediction=model(f,g)
    assert torch.allclose(prediction,torch.tensor([[0.,0.,1.,0.]]).repeat(2,1))
    loss=loss_value(prediction,torch.tensor([[.01,.02,1.,0.],[.02,.01,1.,0.]]))
    assert torch.isfinite(loss);loss.backward()


def test_ridge_and_group_equal_weight_selection():
    rng=np.random.default_rng(4);g=rng.normal(size=(40,16));y=np.zeros((40,4));y[:,0]=g[:,0]*.01;y[:,2]=1
    model=ridge_fit(g,y,1.);prediction=ridge_predict(model,g)
    assert np.isfinite(prediction).all()
    rows=[{'group_id':'big'}]*39+[{'group_id':'small'}]
    geometry=np.tile([0,0,1,0],(40,1));target=geometry.copy().astype(float);target[-1,0]=.1
    metric=score_values(geometry,target,rows)
    assert metric['macro_group_selection_score']==pytest.approx(1.)


def test_readonly_live_row_access_does_not_change_flags(tmp_path):
    path=tmp_path/'annotations.sqlite3'
    row={'human_pose_confirmed':False,'state':'draft'}
    with sqlite3.connect(path) as db:
        db.execute('CREATE TABLE annotations(target_key TEXT,payload TEXT)')
        db.execute('INSERT INTO annotations VALUES (?,?)',('x',json.dumps(row)))
    before=path.read_bytes();assert live_rows(tmp_path)=={'x':row};assert path.read_bytes()==before


def test_human_authorization_validator_never_promotes_source_flags(tmp_path):
    root=tmp_path/'geometry';root.mkdir()
    c=candidate();sensor={'forward_axis':0,'up_axis':2,'forward_sign':1,'up_sign':1,'scale_to_m':None,'axes_confirmed':False,'evidence':'','unit_origin':'unknown_native_units'}
    ruler={'origin':c['center'],'basis':c['basis'],'w':.02,'d':0,'angle':3.,'half_width':.5}
    polygon=[[0.,0.],[10.,0.],[10.,10.],[0.,10.]];token='a'*64
    target={'target_key':'x','frame_id':'f','split':'train','group_id':'g','source_pcd_sha256':'sha','bbox':{'x':0,'y':0,'width':10,'height':10},'size':[10,10]}
    meta={'target_key':'x','polygon':polygon,'sensor':sensor,'candidates':[{'id':1}]}
    (root/(token+'.json')).write_text(json.dumps(meta))
    np.savez(root/(token+'.npz'),source_indices=np.arange(30),xyz=np.random.default_rng(2).normal(size=(30,3)),face_ids=np.ones(30,int))
    row={'source':target,'sensor':sensor,'ruler':ruler,'geometry_token':token,'pose':pose_value(ruler,sensor),
        'target_key':'x','polygon':polygon,'selected_faces':[1],'selected_measured_points':30,'human_pose_confirmed':False,'state':'draft'}
    before=deepcopy(row);value=validate_review(row,target,tmp_path)
    assert row==before and not row['human_pose_confirmed']
    assert value['pose']['position_unit']=='native_unknown'
    row['pose']['x']+=1
    with pytest.raises(ValueError,match='differs_from_ruler'):validate_review(row,target,tmp_path)


def test_validate_requires_measured_support_and_no_deferred(tmp_path):
    target={'target_key':'x','frame_id':'f','split':'train','group_id':'g','source_pcd_sha256':'sha','bbox':{},'size':[10,10]}
    sensor={'forward_axis':0,'up_axis':2,'forward_sign':1,'up_sign':1}
    row={'source':target,'sensor':sensor,'state':'deferred'}
    with pytest.raises(ValueError,match='human_deferred'):validate_review(row,target,tmp_path)
    row['state']='draft'
    with pytest.raises(ValueError,match='missing_ruler'):validate_review(row,target,tmp_path)


def test_portable_predictor_accepts_only_cloud_box_not_ruler(tmp_path):
    from pallet.pose_refinement import SCHEMA
    from pallet.pose_refinement_inference import RefinedPosePredictor
    from pallet.cluster_targets import digest
    profiles=[]
    for branch in ('metric','native_unknown'):
        path=tmp_path/branch;path.mkdir()
        torch.save({'schema':SCHEMA,'model':NormalizedPointNet().state_dict()},path/'model.pt')
        (path/'ridge.json').write_text(json.dumps(ridge_fit(np.zeros((3,16)),np.tile([0,0,1,0],(3,1)),1)))
        profiles.append({'branch':branch,'network':branch+'/model.pt','network_sha256':digest(path/'model.pt'),
            'ridge':branch+'/ridge.json','ridge_sha256':digest(path/'ridge.json'),'selected_family':'geometry','domains':['fixture']})
    (tmp_path/'bundle_config.json').write_text(json.dumps({'schema':SCHEMA,'files':{},'profiles':profiles,'seed':42,'points':64}))
    h,w=24,48;yy,xx=np.mgrid[:h,:w]
    points=np.stack((xx*0+1.6,(w/2-xx)*.02,(h/2-yy)*.01,xx*0+100),axis=-1).reshape(-1,4).astype(np.float32)
    mapping=np.arange(len(points),dtype=np.int32).reshape(h,w)
    predictor=RefinedPosePredictor(tmp_path,allow_native=True)
    metric=predictor.pose(points,mapping,[0,0,w,h],scale_to_m=1.,domain='fixture')
    native=predictor.pose(points,mapping,[0,0,w,h],domain='fixture')
    assert metric['metric_pose_estimate'] is not None and native['metric_pose_estimate'] is None
    assert metric['pose_estimate']['x']==pytest.approx(native['pose_estimate']['x'])
    assert native['pose_estimate']['position_unit']=='native_unknown'
    assert metric['pose_estimate']['reference_point']=='fork_face_width_center'
    assert metric['pose_estimate']['z'] is None and not metric['human_pose_confirmed']
    with pytest.raises(ValueError,match='outside'):predictor.pose(points,mapping,[0,0,w,h],domain='untrained')
    with pytest.raises(ValueError,match='Unknown units'):RefinedPosePredictor(tmp_path).pose(points,mapping,[0,0,w,h],domain='fixture')
