"""Operator semantics and experiment isolation checks for official adapters."""
import json

import numpy as np
import pytest
import torch

from pallet.pose_benchmark_models import BallGroup, KNN, fps_indices, ROOT
from pallet.pose_refinement import decoded, residual_target


def test_fps_matches_independent_numpy_reference():
    x = np.random.default_rng(4).normal(size=(2, 37, 3)).astype('float32')
    expected = []
    for points in x:
        distance = np.full(len(points), np.inf)
        picks = [0]
        for _ in range(12):
            distance = np.minimum(distance, ((points - points[picks[-1]]) ** 2).sum(-1))
            picks.append(int(distance.argmax()))
        expected.append(picks[:12])
    np.testing.assert_array_equal(fps_indices(torch.tensor(x), 12).numpy(), expected)


def test_ball_query_uses_source_order_and_duplicate_first_not_nearest_order():
    points = torch.tensor([[[.08, 0, 0], [.01, 0, 0], [.3, 0, 0]]])
    query = torch.zeros(1, 1, 3)
    features = torch.tensor([[[8., 1., 3.]]], requires_grad=True)
    dp, grouped = BallGroup(dict(radius=.1, nsample=4, normalize_dp=True))(query, points, features)
    torch.testing.assert_close(grouped, torch.tensor([[[[8., 1., 8., 8.]]]]))
    torch.testing.assert_close(dp[0, 0, 0], torch.tensor([.8, .1, .8, .8]))
    grouped.sum().backward()
    torch.testing.assert_close(features.grad, torch.tensor([[[3., 1., 0.]]]))


def test_group_all_matches_official_absolute_coordinates():
    points = torch.randn(2, 6, 3)
    features = torch.randn(2, 8, 6)
    dp, grouped = BallGroup(dict(radius=None, nsample=None, normalize_dp=True))(points, points, features)
    torch.testing.assert_close(dp, points.transpose(1, 2).unsqueeze(2))
    torch.testing.assert_close(grouped, features.unsqueeze(2))


def test_knn_indices_are_exact_euclidean_neighbours():
    points = torch.tensor([[[3., 0, 0], [0., 0, 0], [1., 0, 0], [5., 0, 0]]])
    distance, indices = KNN(2)(points, torch.tensor([[[.2, 0, 0]]]))
    assert indices.tolist() == [[[1, 2]]]
    torch.testing.assert_close(distance, torch.tensor([[[.2, .8]]]))


def test_pose_decoding_preserves_native_and_metric_units():
    for scale in (1., 1000.):
        base = np.array([2., -.1, .3]) * scale
        width = 1.2 * scale
        direction = np.array([np.cos(.2), np.sin(.2)])
        row = dict(pose=dict(x=2.04 * scale, y=-.12 * scale, theta_degrees=17.))
        residual = residual_target(row, base, width, direction)
        output = decoded(residual, base, np.array(width), direction)
        np.testing.assert_allclose(output[:2], [row['pose']['x'], row['pose']['y']], rtol=1e-6)
        np.testing.assert_allclose(np.degrees(np.arctan2(output[3], output[2])), 17., atol=1e-5)


def test_frozen_protocol_contains_only_original_train_and_disjoint_groups():
    if not (ROOT / 'protocol.json').exists():
        pytest.skip('Benchmark artifacts are not part of a clean source checkout')
    protocol = json.loads((ROOT / 'protocol.json').read_text())
    rows = [json.loads(line) for line in open(protocol['config']['frozen_labels'])]
    bykey = {r['target_key']: r for r in rows}
    for branch, folds in protocol['folds'].items():
        seen = []
        for fold in folds:
            assert all(bykey[k]['split'] == 'train' and bykey[k]['branch'] == branch
                       for k in fold['fit'] + fold['validation'])
            assert not ({bykey[k]['group_id'] for k in fold['fit']} &
                        {bykey[k]['group_id'] for k in fold['validation']})
            seen += fold['validation']
        assert len(seen) == len(set(seen)) == protocol['original_train_counts'][branch]


def test_bootstrap_weights_groups_not_frame_counts():
    from pallet.pose_benchmark_results import paired_group_interval
    target = np.array([[0, 0, 1, 0], [0, 0, 1, 0]], dtype=np.float32)
    prediction = target.copy(); prediction[:, 0] = [.01, .03]
    rows = [{'group_id': 'a'}, {'group_id': 'b'}]
    first = paired_group_interval([prediction], target, rows)
    repeated = paired_group_interval([np.repeat(prediction, [1, 19], axis=0)],
                                     np.repeat(target, [1, 19], axis=0), [rows[0]] + [rows[1]] * 19)
    np.testing.assert_allclose([first[k] for k in ('mean', 'lower', 'upper')],
                               [repeated[k] for k in ('mean', 'lower', 'upper')], atol=1e-7)


def test_failed_preprocessing_counts_against_full_denominator():
    from pallet.pose_benchmark_results import evaluation_stats
    target = np.array([[0, 0, 1, 0], [0, 0, 1, 0]], dtype=np.float32)
    result = evaluation_stats(target.copy(), [{'branch': 'metric', 'group_id': 'g'}] * 2,
                               {'y': target, 'width': np.ones(2)}, total=3)
    assert result['failed_preprocessing'] == 1
    assert result['success_count'] == 2
    assert result['full_denominator_success_rate'] == 2 / 3


def test_accelerated_results_do_not_reuse_old_batch8_paths(tmp_path,monkeypatch):
    import pallet.pose_benchmark as benchmark
    import pallet.pose_benchmark_results as results
    monkeypatch.setattr(benchmark,'ROOT',tmp_path)
    monkeypatch.setattr(results,'ROOT',tmp_path)
    initial=results.result_path('pointnext','metric')
    (tmp_path/'refinement_protocol.json').write_text('{}')
    fast=results.result_path('pointnext','metric')
    assert '/screen/' in str(initial)
    assert '/accelerated/' in str(fast)
    assert fast!=initial
    assert results.result_path('pointnext','metric',recipe='screen')==initial


def test_acceleration_binds_parent_without_rewriting_it(tmp_path,monkeypatch):
    import pallet.pose_benchmark as benchmark
    parent=tmp_path/'protocol.json'
    parent.write_text(json.dumps({'config':{'epochs':80,'batch':16}}))
    evidence=tmp_path/'throughput.json';evidence.write_text('{}')
    policy=tmp_path/'acceleration.json'
    policy.write_text(json.dumps(dict(memory_and_speed_evidence=[str(evidence)],end_to_end_batch=32,
                                      batch=32,evaluation_batch=64,embedding_batch=32,epochs=80)))
    monkeypatch.setattr(benchmark,'ROOT',tmp_path)
    monkeypatch.setattr(benchmark,'ACCELERATION',policy)
    original=parent.read_bytes()
    benchmark.freeze_refinement_protocol()
    config=benchmark.recipe_config('accelerated')
    assert config['end_to_end_batch']==32 and config['evaluation_batch']==64
    assert parent.read_bytes()==original
    assert benchmark.recipe_config('screen')['batch']==16
    policy.write_text(policy.read_text()+' ')
    with pytest.raises(ValueError,match='binding changed'):
        benchmark.recipe_config('accelerated')
