"""Metric-compatibility and original-paper transcription regression checks."""
import importlib.util
from pathlib import Path

import numpy as np
import pytest

SPEC=importlib.util.spec_from_file_location('gap',Path(__file__).parents[1]/'scripts/analyze_pose_paper_gap_v1.py')
gap=importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(gap)


def test_ground_scene_accuracy_is_not_joint_success_rate():
    paper=gap.paper_tables()
    rows=paper['ground_scene_reconstructed']
    assert rows['included_n']==6 and rows['included_passes_50mm_5deg']==5
    assert rows['all_n']==8 and rows['all_passes_50mm_5deg']==6
    assert rows['included_planar_error_mm']>20
    assert paper['ground_scene_reported']['accuracy_is_not_50mm_5deg_joint_rate']


def test_original_table4_percentages_recomputed_not_silently_repeated():
    table=gap.paper_tables()['table4']
    assert table['recomputed_error_reduction_vs_FPFH_percent']==pytest.approx((.017559-.011715)/.017559*100)
    assert table['recomputed_error_reduction_vs_FPFH_percent']!=pytest.approx(table['printed_error_reduction_vs_FPFH_percent'])
    assert table['recomputed_time_reduction_vs_FPFH_percent']!=pytest.approx(table['printed_time_reduction_vs_FPFH_percent'])


def test_pose_RMSE_MAE_and_per_axis_MAE_are_distinct():
    labels={'a':dict(pose=dict(x=0.,y=0.,theta_degrees=0.)),
            'b':dict(pose=dict(x=0.,y=0.,theta_degrees=0.)),
            'c':dict(pose=dict(x=0.,y=0.,theta_degrees=0.))}
    records=[dict(target_key='a',state='complete',pose=[.003,.004,0.]),
             dict(target_key='b',state='complete',pose=[.006,.008,0.]),
             dict(target_key='c',state='failed',reason='no_output')]
    value=gap.summarize(records,labels)
    assert value['position']['mean']==pytest.approx(7.5)
    assert value['MAE_source_X_mm']==pytest.approx(4.5)
    assert value['pose_XY_RMSE_mm']==pytest.approx(np.sqrt(62.5))
    assert value['full_denominator_joint_rate']==pytest.approx(2/3)
    assert value['no_output']==1
