"""New authorization does not relax identity, valid pixels or honest evaluation."""
from collections import Counter

import numpy as np
import pytest
import torch

from pallet.mask_annotation_full_data import context, supervision_valid
from pallet.mask_annotation_full_train import epoch_indices, m1_loss, rf_target, CONFIGS, augment
from pallet.mask_model_improvement_adapter import native_logits


def test_every_image_and_component_is_guaranteed_each_epoch():
    records=[dict(component='large') for _ in range(113)]+[dict(component=f'small{i}') for i in range(193)]
    plan=epoch_indices(records,0);assert len(plan)==2*len(records)
    assert set(plan)==set(range(len(records)))
    counts=Counter(records[i]['component'] for i in plan)
    assert len(counts)==194 and min(counts.values())>=1


def test_balanced_extra_component_round_does_not_follow_large_group_size():
    records=[dict(component='large') for _ in range(20)]+[dict(component='small')]
    plan=epoch_indices(records,0);counts=Counter(records[i]['component'] for i in plan)
    assert abs((counts['large']-20)-(counts['small']-1))<=1


def test_sampling_is_reproducible_but_changes_by_epoch():
    records=[dict(component=str(i%3)) for i in range(20)]
    assert epoch_indices(records,2)==epoch_indices(records,2)
    assert epoch_indices(records,2)!=epoch_indices(records,3)


def test_roi_depends_only_on_original_box_and_image_not_label():
    box=dict(x=0,y=163.805,width=38.527,height=20.191)
    assert context(box,[352,264])==[0,147,87,200]


def test_known_neighbor_is_ignored_but_actual_manual_positives_are_not_erased():
    roi=[0,0,20,20];mask=np.zeros((20,20),np.uint8);mask[3:6,3:6]=1
    rows=[dict(target_key='other',bbox=dict(x=0,y=0,width=10,height=10))]
    valid=supervision_valid(roi,rows,'this',mask)
    assert valid[1,1]==0 and valid[4,4]==1 and valid[15,15]==1


def test_valid_mask_blocks_invalid_pixels_and_keeps_mask_gradient():
    x=torch.randn(1,4,5,requires_grad=True);y=torch.zeros_like(x);y[:,1:3,1:3]=1;v=torch.zeros_like(x);v[:,1:3,1:4]=1
    loss=m1_loss(x,y,v);loss.backward()
    assert torch.isfinite(loss) and (x.grad[v==0]==0).all() and x.grad[v>0].abs().sum()>0
    changed=x.detach().clone();changed[v==0]=10000
    assert torch.allclose(m1_loss(changed,y,v),loss.detach())


def test_rfdetr_single_category_targets_are_normalized_no_original_class_feature():
    m=torch.zeros(8,10);m[2:6,3:9]=1;t=rf_target(m,torch.ones_like(m))
    assert t['labels'].tolist()==[0]
    assert torch.allclose(t['boxes'],torch.tensor([[.6,.5,.6,.5]]))
    assert set(t)=={'labels','boxes','masks','pixel_valid'}


def test_empty_rf_mask_is_not_fabricated_as_a_target():
    with pytest.raises(ValueError,match='Empty'):
        rf_target(torch.zeros(4,4),torch.ones(4,4))


def test_no_old_validation_selection_or_holdouts_in_new_configs():
    assert CONFIGS['m1']['epochs']==30 and CONFIGS['m2']['epochs']==20
    assert CONFIGS['m1']['edge_weight']==0
    assert not any(k in cfg for cfg in CONFIGS.values() for k in ('val','best_validation','calibration'))


def test_raw_logits_native_mapping_is_not_double_threshold():
    x=torch.tensor([[[-.2,.1],[.3,-.4]]])[0]
    transform=dict(output_size=[2,2],padding_left_top=[0,0],scaled_size=[2,2],native_size=[2,2])
    assert torch.equal(native_logits(x,transform),x)


def test_photometric_augmentation_preserves_padding_and_shape():
    mean=torch.tensor([.485,.456,.406])[None,:,None,None];std=torch.tensor([.229,.224,.225])[None,:,None,None]
    image=(torch.full((2,3,8,8),.5)-mean)/std;valid=torch.ones(2,1,8,8);valid[:,:,:2]=0
    output=augment(image,valid);decoded=output*std+mean
    assert output.shape==image.shape and torch.isfinite(output).all() and decoded[:,:,:2].abs().max()<1e-7
