"""Synthetic math, no-leakage gates and full-denominator reporting; no online writes."""
import json

import numpy as np
import pytest

from pallet import pose_paper_methods as m
from pallet import pose_paper_benchmark as b
from pallet import pose_paper_results as r
from pallet import pose_paper_data as d


def plane():
    y,z=np.meshgrid(np.linspace(-.6,.6,64),np.linspace(-.1,.1,24))
    xyz=np.column_stack((np.full(y.size,2.),y.ravel(),z.ravel()))
    uv=np.column_stack(np.meshgrid(np.arange(64),np.arange(24))).reshape(-1,2)
    vv,uu=np.mgrid[:24,:64]
    return xyz,np.column_stack((uu.ravel(),vv.ravel()))


def test_rigid_fit_recovers_transform_and_reflection_is_not_rotation():
    p=np.random.default_rng(4).normal(size=(80,3));rot=m.rotation(.37);t=np.array([2.,-.1,.03])
    result,shift=m.rigid_fit(p,p@rot.T+t)
    np.testing.assert_allclose(result,rot,atol=1e-12)
    np.testing.assert_allclose(shift,t,atol=1e-12)
    assert np.linalg.det(result)==pytest.approx(1.)


def test_voxel_retains_measured_points_and_caps_deterministically():
    p=np.random.default_rng(5).normal(size=(3000,3))
    a=m.voxel_points(p,maximum=96);c=m.voxel_points(p,maximum=96)
    np.testing.assert_array_equal(a,c)
    assert len(a)<=96 and all(any(np.array_equal(v,q) for q in p) for v in a)


def test_gaussian_weights_peak_at_mean_not_smallest_distance():
    weights=m.gaussian_weights([1.,2.,3.])
    assert weights[1]>weights[0] and weights[0]==pytest.approx(weights[2])
    assert np.isfinite(m.gaussian_weights([2.,2.,2.])).all()


def test_descriptors_finite_and_adaptive_radius_is_dp_to_2dp():
    p=np.random.default_rng(3).normal(0,.1,(160,3))+[2.,0.,0.]
    f,keys,radius=m.descriptors(p,True)
    dp=m.cKDTree(p).query(p,k=2)[0][:,1].mean()
    assert f.shape==(160,33) and np.isfinite(f).all()
    assert radius.min()>=dp-1e-12 and radius.max()<=2*dp+1e-12
    assert len(set(keys.tolist()))==len(keys)


def test_pila_fixed_box_backend_preserves_center_and_angle():
    p,_=plane();pose,evidence=m.pila_geometry(p)
    np.testing.assert_allclose(pose,[2.,0.,0.],atol=1e-8)
    assert evidence['inliers']==len(p)


def test_region_growing_uses_organized_adjacency():
    p,uv=plane();regions=m.plane_regions(p,uv)
    assert regions and max(mask.sum() for _,_,mask in regions)==len(p)


def test_registration_does_not_fake_initialization_if_no_ISS():
    p,_=plane()
    with pytest.raises(ValueError,match='ISS'):
        m.register(p,p,np.zeros((len(p),33)),np.zeros((len(p),33)),np.array([],int),np.array([],int))


def test_template_fit_rejects_holdout_before_reading_inputs(tmp_path,monkeypatch):
    monkeypatch.setattr(d,'ROOT',tmp_path)
    with pytest.raises(ValueError,match='Holdout'):
        b.build_bank('bad',[dict(target_key='target',split='test')])


def test_full_denominator_failure_and_360_degree_angle_wrap():
    rows=[dict(target_key='a',group_id='g',domain='d',pose=dict(x=0.,y=0.,theta_degrees=179.)),
          dict(target_key='b',group_id='h',domain='d',pose=dict(x=0.,y=0.,theta_degrees=0.))]
    predictions=[dict(target_key='a',state='complete',pose=[.01,0.,np.deg2rad(-179.)]),
                 dict(target_key='b',state='failed',pose=None,reason='no_plane')]
    stats,values=r.evaluate_records(rows,predictions,{'a':1.,'b':1.})
    assert stats['total']==2 and stats['predictions']==1 and stats['success_count']==1
    assert stats['success_rate']==.5 and stats['position_mean_mm']==10.
    assert stats['angle_mean_deg']==pytest.approx(2.)
    assert values[1]['score']==100 and values[1]['position_mm'] is None


def test_duplicate_or_missing_predictions_are_rejected():
    rows=[dict(target_key='a')]
    with pytest.raises(ValueError,match='identities'):
        r.evaluate_records(rows,[],{})


def test_pairing_counts_rescues_and_new_regressions():
    ref=[dict(target_key=str(i),group_id='g',state='complete',success=s,score=1.,position_mm=1.,angle_deg=1.) for i,s in enumerate([True,True,False,False])]
    other=[dict(v,success=s) for v,s in zip(ref,[True,False,True,False])]
    pair=r.paired(ref,other)
    assert [pair[k] for k in ('both_pass','rescued','regressed','both_fail')]==[1,1,1,1]
    assert pair['macro_score_delta_95CI']==[0.,0.]


def test_html_table_escapes_untrusted_strings():
    result=r.table(['<script>'],[['<img src=x>']])
    assert '&lt;script&gt;' in result and '<img' not in result


def test_frozen_original_group_splits_and_no_manual_features():
    path=d.ROOT/'protocol.json'
    if not path.exists():pytest.skip('Optional frozen v5 cohort')
    protocol=json.loads(path.read_text())
    seen=set()
    for fold in protocol['branches']['metric']['folds']:
        assert not set(fold['fit_keys'])&set(fold['validation_keys'])
        assert not set(fold['fit_groups'])&set(fold['validation_groups'])
        assert not seen&set(fold['validation_keys'])
        seen.update(fold['validation_keys'])
    assert len(seen)==1767
    features=d.read_rows(d.ROOT/'dataset/features.jsonl')
    assert len(features)==3593 and not any(v['human_polygon_face_ruler_are_inputs'] for v in features)


def test_offline_report_end_to_end_on_synthetic_metrics(tmp_path,monkeypatch):
    monkeypatch.setattr(d,'ROOT',tmp_path)
    (tmp_path/'snapshot').mkdir()
    (tmp_path/'snapshot/manifest.json').write_text(json.dumps(dict(created_at='frozen',eligible=2,counts=dict(train=2,val=2,test=2))))
    choice=dict(method='pila_geometry',threshold_m=.015,score=.2,failures=0)
    (tmp_path/'paper_selection.json').write_text(json.dumps(dict(selected={'pila_geometry':choice},entries=[choice])))
    (tmp_path/'learning_selection.json').write_text(json.dumps(dict(CV_scores=[.2,.2,.2],refit_epoch=10)))
    (tmp_path/'selection_frozen.json').write_text(json.dumps(dict(created_at='frozen',choices={})))
    rows=[dict(target_key=str(i),group_id='g',domain='d',pose=dict(x=2.,y=0.,theta_degrees=0.)) for i in range(2)]
    predictions=[dict(target_key=str(i),state='complete',pose=[2.,0.,0.],seconds=None) for i in range(2)]
    summary,values=r.evaluate_records(rows,predictions,{'0':1.,'1':1.})
    summary['paired_vs_geometry']=r.paired(values,values)
    names=['geometry_ROI_fallback','pila_geometry','pila_geometry_common_fallback']
    cohort=dict(rows=rows,summaries={n:summary for n in names},targets={n:values for n in names})
    monkeypatch.setattr(r,'cohort',lambda _:cohort)
    monkeypatch.setattr(r,'case_cards',lambda *_:('',[]))
    monkeypatch.setattr(r,'package',lambda:None)
    monkeypatch.setattr(r,'verify_html',lambda:None)
    result=r.report()
    html=(tmp_path/'report/index.html').read_text()
    assert result['robot_command_eligible'] is False
    assert 'connect-src' in html and "'none'" in html and 'data:text/csv;base64,' in html
    assert 'fetch(' not in html and 'https://' not in html
    assert (tmp_path/'report/target_metrics.csv').exists()
