import importlib.util
from pathlib import Path

import numpy as np

spec=importlib.util.spec_from_file_location('remaining_requests',Path(__file__).resolve().parents[1]/'scripts/build_mask_remaining_requests.py')
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)


def test_all_remaining_classes_exclude_completed_five():
    assert len(module.CLASSES)==17
    assert set(module.CLASSES)==set(range(1,23))-{1,2,9,10,15}


def test_medoid_distances_match_direct_other_frame_computation():
    keys=['a','b','c','d'];rows={k:dict(frame_id=f) for k,f in zip(keys,['same','same','other','third'])}
    vectors=np.array([[1.,0],[0,1],[.5,.5],[-1,0]])
    distances=module.medoid_statistics(keys,vectors,rows)
    for i,key in enumerate(keys):
        others=[j for j,k in enumerate(keys) if rows[k]['frame_id']!=rows[key]['frame_id']]
        expected=np.mean([np.sum((vectors[i]-vectors[j])**2) for j in others])
        assert np.isclose(distances[key],expected)


def test_any_modified_history_stays_protected_after_restoring_rectangle():
    row=dict(bbox=dict(x=1,y=2,width=10,height=5));rectangle=module.rectangle(row)
    current={'a':dict(polygon=rectangle,state='draft')}
    events=[(1,'a',1,'raw',dict(polygon=[[2,2],[11,2],[11,7],[1,7]],state='draft'))]
    assert module.protected_history(current,events,{'a':row})=={'a'}


def test_pose_only_rectangle_remains_eligible_but_confirmed_does_not():
    row=dict(bbox=dict(x=1,y=2,width=10,height=5));rectangle=module.rectangle(row)
    current={'a':dict(polygon=rectangle,state='draft',pose={'x':1}),
        'b':dict(polygon=rectangle,state='draft',human_pose_confirmed=True)}
    assert module.protected_history(current,[],{'a':row,'b':row})=={'b'}


def test_medoid_has_zero_distance_without_other_frames():
    rows={'a':dict(frame_id='same'),'b':dict(frame_id='same')}
    assert module.medoid_statistics(['a','b'],[[1.,0],[0,1]],rows)=={'a':0.,'b':0.}


def test_task_selection_is_distinct_and_requires_explicit_visual_approval():
    rows={};usable={}
    for cls in module.CLASSES:
        for i in range(4):
            key=f'{cls}-{i}'
            rows[key]=dict(frame_id=key,final_class_id=cls,split='train',policy_id='same-policy',
                viewpoint_candidate='unknown',group_id=f'group-{i}')
            usable[key]=dict(no_pose_current_or_history=True,exact_view_human_template_absent=True,
                medoid_mean_squared_patch_distance=0.,quality=dict(clarity_score=.8,bbox_area_native_pixels=3000),
                usable_compatible_neighbor_count=3)
    decisions={k:dict(approved=not k.endswith('-3')) for k in rows}
    selected=module.select_tasks(rows,usable,3,decisions,True)
    assert len(selected)==51 and len({rows[k]['frame_id'] for k in selected})==51
    assert all(not k.endswith('-3') for k in selected)
    assert module.select_tasks(rows,usable,3,{},True)==[]


def test_scarce_class_gets_shared_frame_first_and_no_duplicate_credit():
    rows={
        'scarce':dict(frame_id='shared',final_class_id=19,split='train',policy_id='p',viewpoint_candidate='unknown',group_id='g'),
        'common':dict(frame_id='shared',final_class_id=3,split='train',policy_id='p',viewpoint_candidate='unknown',group_id='g'),
        'other':dict(frame_id='other',final_class_id=3,split='train',policy_id='p',viewpoint_candidate='unknown',group_id='g2')}
    usable={k:dict(no_pose_current_or_history=True,exact_view_human_template_absent=True,
        medoid_mean_squared_patch_distance=0.,quality=dict(clarity_score=.8,bbox_area_native_pixels=3000),
        usable_compatible_neighbor_count=1) for k in rows}
    selected=module.select_tasks(rows,usable,1)
    assert set(selected)=={'scarce','other'}


def test_native_quality_gates_are_not_relaxed_for_new_classes():
    row=dict(bbox=dict(x=5,y=5,width=49,height=20),size=[120,80])
    value,reason=module.native_quality(row,None)
    assert value is None and reason=='bbox_too_small_for_manual_tracing'
