from __future__ import annotations

import copy
from types import SimpleNamespace

import numpy as np
from PIL import Image
import pytest
from pycocotools.mask import decode

from pallet.fork_face_anylabeling import protected_write, rasterize
from pallet.instance_segmentation_seed import audit_document, bbox, letterbox, restore_mask, rle, split_groups, transform_mask
from pallet.instance_segmentation_completion import (box_pixels, closed_holes, crop_retry, deduplicate,
    machine_shapes, match_masks, ownership, render_shapes)


def upstream(size, points, shape_type):
    assert shape_type=='polygon'
    return rasterize(points,size)


def shape(points, label='pallet', kind='polygon'):
    return {'label':label,'points':points,'shape_type':kind,'group_id':None,'flags':{}}


def ring(x0,y0,x1,y1,label='pallet'):
    return shape([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],label)


def candidate(mask,score=.9):
    return {'mask':mask,'score':score,'bbox':bbox(mask)}


def test_two_faces_and_holes_are_distinct_instances():
    document={'shapes':[ring(1,1,12,16),ring(18,1,27,16),ring(4,5,7,9,'__hole__'),
                        shape([[0,0],[29,19]],kind='rectangle')]}
    instances,reasons,rectangles=audit_document(document,(20,30),upstream)
    assert not reasons and rectangles==1 and len(instances)==2
    assert len(instances[0]['hole_shapes'])==1 and not instances[0]['mask'][6,5]
    assert instances[0]['mask'][2,2] and not (instances[0]['mask']&instances[1]['mask']).any()
    assert instances[0]['bbox']==[1,1,12,16]
    assert np.array_equal(decode(rle(instances[0]['mask']))>0,instances[0]['mask'])


def test_nested_positives_quarantined_without_repair():
    document={'shapes':[ring(1,1,18,18),ring(3,3,9,9),ring(4,4,6,6,'__hole__')]}
    before=copy.deepcopy(document)
    _, reasons,_=audit_document(document,(20,20),upstream)
    assert any('positive_overlap_or_nested' in r for r in reasons)
    assert any('ambiguous_hole' in r for r in reasons)
    assert document==before


def test_unowned_hole_is_not_an_instance():
    instances,reasons,_=audit_document({'shapes':[ring(1,1,8,8),ring(13,13,17,17,'__hole__')]},(20,20),upstream)
    assert len(instances)==1 and reasons==['ambiguous_hole:1']


@pytest.mark.parametrize('points', [[[0,0],[20,1],[1,2]], [[0,0],[2,float('nan')],[1,2]],
                                    [[1,1],[9,9],[1,9],[9,1]], [[1,1],[2,2]]])
def test_invalid_coordinates_quarantined(points):
    instances,reasons,_=audit_document({'shapes':[shape(points)]},(20,20),upstream)
    assert not instances and any(r.startswith('invalid_shape:') for r in reasons)


def test_rectangle_only_is_not_segmentation_negative():
    instances,reasons,rectangles=audit_document({'shapes':[shape([[0,0],[19,19]],kind='rectangle')]},(20,20),upstream)
    assert instances==[] and reasons==[] and rectangles==1


@pytest.mark.parametrize('size',[(240,96),(96,240),(768,384),(384,768),(37,81)])
def test_letterbox_coordinate_restore_and_rgb(size):
    w,h=size; source=np.zeros((h,w),np.uint8);source[h//4:3*h//4,w//4:3*w//4]=255
    prepared,t=letterbox(Image.fromarray(source))
    assert prepared.mode=='RGB' and prepared.size==(768,768)
    np.testing.assert_array_equal(restore_mask(transform_mask(source>0,t),t),source>0)
    rgb=np.asarray(prepared);assert np.array_equal(rgb[...,0],rgb[...,1])
    assert abs(t['resized_width']/w-t['resized_height']/h)<1/min(w,h)


def test_bbox_and_float_parent_use_native_pixel_conventions():
    mask=np.zeros((10,12),bool);mask[7,9]=True
    assert bbox(mask)==[9,7,1,1]
    pixels=box_pixels([1.2,2.8,2.1,3.3],(10,12))
    assert bbox(pixels)==[1,2,3,5]
    with pytest.raises(ValueError):bbox(np.zeros((3,3),bool))


def test_group_split_reproducible_no_leakage_and_rare_train():
    frames=[{'group_id':str(i),'domain':'common','instances':[{'hole_shapes':[{}] if i<3 else []}]} for i in range(10)]
    frames += [{'group_id':'rare','domain':'only_one','instances':[{'hole_shapes':[]}]}]
    split=split_groups(frames,42)
    assert split==split_groups(list(reversed(frames)),42)
    assert split['rare']=='train'
    assert sum(split[str(i)]=='valid' for i in range(3))>=2


def test_closed_holes_exclude_open_channels():
    mask=np.zeros((20,20),bool);mask[2:18,2:18]=True;mask[6:10,6:10]=False
    assert closed_holes(mask).sum()==16
    mask[2:7,7]=False
    assert not closed_holes(mask).any()


@pytest.mark.parametrize('seed',range(5))
def test_polygon_holes_pixel_exact_with_thin_and_disconnected_parts(seed):
    rng=np.random.default_rng(seed); mask=rng.random((27,31))>.35
    mask[3:23,5:25]=True;mask[8:15,10:18]=False;mask[25,:]=False
    shapes=machine_shapes(mask,1)
    assert set(s['label'] for s in shapes)=={'pallet','__hole__'}
    assert all(s['group_id']==1 and s['shape_type']=='polygon' for s in shapes)
    assert np.array_equal(render_shapes(shapes,mask.shape,upstream)[1],mask)


def test_neighbor_faces_kept_other_parent_not_stolen_and_duplicates_suppressed():
    main=box_pixels([20,20,20,30],(80,100));side=box_pixels([41,22,8,26],(80,100))
    other=box_pixels([60,20,20,30],(80,100))
    raw=[candidate(main),candidate(main,.7),candidate(side,.8),candidate(other,.95)]
    unique=deduplicate(raw)
    assert len(unique)==3
    owned=ownership(unique,[[20,20,20,30],[60,20,20,30]],0,.5)
    assert len(owned)==2
    assert {p['ownership'] for p in owned}=={'main','adjacent_side'}
    assert all(not (p['mask']&other).any() for p in owned)


def test_duplicate_optimization_matches_full_native_masks():
    from pallet.instance_segmentation_completion import iou
    rng=np.random.default_rng(42)
    candidates=[]
    for number in range(60):
        mask=np.zeros((120,180),bool);x=int(rng.integers(0,130));y=int(rng.integers(0,80))
        mask[y:y+30,x:x+40]=rng.random((30,40))>.1
        candidates.append(dict(candidate(mask,float(rng.random())),prediction_index=number))
        if number%4==0:candidates.append(dict(candidate(mask,float(rng.random())),prediction_index=number+100))
    expected=[]
    for p in sorted(candidates,key=lambda c:(-c['score'],c['prediction_index'])):
        if not any(iou(p['mask'],k['mask'])>.75 or (p['mask']&k['mask']).sum()/min(p['mask'].sum(),k['mask'].sum())>.95 for k in expected):
            expected.append(p)
    assert [p['prediction_index'] for p in deduplicate(candidates)]==[p['prediction_index'] for p in expected]


def test_low_confidence_fallback_is_nonempty_mask_no_rectangle_fabrication():
    main=box_pixels([20,20,20,30],(80,100))
    owned=ownership([candidate(main,.07)],[[20,20,20,30]],0,.5)
    assert len(owned)==1 and owned[0]['low_confidence'] and np.array_equal(owned[0]['mask'],main)
    assert ownership([],[[20,20,20,30]],0,.5)==[]


def test_crop_retry_restores_native_coordinates():
    class Model:
        def predict(self,image,**kwargs):
            mask=np.asarray(image)[...,0]>0
            return SimpleNamespace(mask=np.array([mask]),confidence=np.array([.9]),class_id=np.array([0]))
    results=crop_retry(Model(),Image.new('RGB',(200,100),'white'),[40,30,20,20])
    assert len(results)==1 and results[0]['mask'].shape==(100,200)
    assert results[0]['bbox']==[28,18,44,44]
    assert results[0]['inference_mode']=='expanded_parent_crop'


def test_matching_uses_masks_and_accounts_for_missing_faces():
    a=box_pixels([1,1,5,5],(20,20));b=box_pixels([12,12,5,5],(20,20))
    matches=match_masks([a,b],[candidate(b,.9),candidate(a,.1)])
    assert matches==[(0,1,1.),(1,0,1.)]
    assert match_masks([a],[])==[]


def test_protected_writer_refuses_human_edits(tmp_path):
    path=tmp_path/'native.json';protected_write(path,b'original');path.write_bytes(b'human edit')
    with pytest.raises(ValueError):protected_write(path,b'original')
    assert path.read_bytes()==b'human edit'


def test_preview_keeps_original_float_bbox_dictionary(tmp_path,monkeypatch):
    import io
    import pallet.instance_segmentation_report as reporting
    buffer=io.BytesIO();Image.new('L',(120,60),80).save(buffer,format='PNG')
    monkeypatch.setattr(reporting,'native_image',lambda ctx,key:buffer.getvalue())
    reporting.preview({'output':tmp_path},{'frame_key':'f','faces':[],
        'original_parent_bbox':{'x':10.25,'y':20.5,'width':40.5,'height':10.25}},tmp_path)
    assert Image.open(tmp_path/'previews/f.png').size==(640,320)
