import hashlib
import json
from pathlib import Path

import numpy as np
import pytest

import pallet.fork_face_simplify as module
from pallet.fork_face_simplify import (
    DEFAULT_CONFIG, cleanup_variants, encoded, fill_polygons, grouped_pixels,
    load_upstream, main, pixel_metrics, protected_write, recheck_verified,
    select_pilot, simplify_mask,
)
from test_fork_face_anylabeling import source


@pytest.fixture
def upstream():
    return load_upstream(DEFAULT_CONFIG['upstream_shape_source'],DEFAULT_CONFIG['upstream_shape_sha256'])


def accepted(mask, upstream, bbox=None, forbidden=None):
    bbox=bbox or {'width':mask.shape[1],'height':mask.shape[0]}
    result=simplify_mask(mask,bbox,DEFAULT_CONFIG,upstream,forbidden)
    assert result['status']=='simplified_accepted',result
    actual=fill_polygons(result['polygons'],mask.shape,upstream)
    assert result['iou']>=.95
    assert pixel_metrics(mask,actual)=={k:result[k] for k in pixel_metrics(mask,actual)}
    assert len(result['polygons'])<=12
    assert sum(map(len,result['polygons']))<=128
    assert all(3<=len(p)<=24 for p in result['polygons'])
    return result,actual


def test_major_holes_nested_islands_and_split_raster_match(upstream):
    mask=np.zeros((40,70),bool);mask[2:38,2:68]=True
    mask[8:31,12:55]=False;mask[15:24,25:36]=True
    result,actual=accepted(mask,upstream)
    assert not actual[8:31,12:55][~mask[8:31,12:55]].any()
    assert actual[15:24,25:36].all()
    assert len(result['polygons'])>=3


@pytest.mark.parametrize('size',[(1,1),(1,18),(21,1),(5,6),(80,160)])
def test_singleton_thin_small_targets_and_image_edges(size,upstream):
    mask=np.ones(size,bool)
    result,actual=accepted(mask,upstream)
    assert np.array_equal(mask,actual)
    assert all(0<=x<size[1] and 0<=y<size[0] for p in result['polygons'] for x,y in p)


def test_disconnected_structures_do_not_get_bridged(upstream):
    mask=np.zeros((30,60),bool);mask[3:22,2:24]=True;mask[5:27,40:56]=True
    result,actual=accepted(mask,upstream)
    assert not actual[:,25:39].any()
    assert len(result['polygons'])==2


def test_tiny_components_and_holes_can_be_removed_but_source_iou_is_measured(upstream):
    mask=np.zeros((34,55),bool);mask[4:30,4:51]=True
    mask[9,12]=False;mask[17,41]=False;mask[1,1]=True
    result,actual=accepted(mask,upstream)
    assert result['vertex_count']<=8
    assert result['added_pixels']==2 and result['deleted_pixels']==1
    assert result['iou']<1


def test_spanning_thin_components_and_holes_protected_even_with_small_area():
    mask=np.zeros((14,24),bool);mask[4:10,4:20]=True;mask[0,1:8]=True
    mask[6,8:15]=False
    for cleaned,fg,holes,info in cleanup_variants(mask,{'width':24,'height':14},DEFAULT_CONFIG):
        assert cleaned[0,1:8].all()
        assert not cleaned[6,8:15].any()
        assert fg[0,1:8].all() and holes[6,8:15].all()


def test_complex_fragmented_positive_has_redraw_identity_and_no_huge_polygons(upstream):
    mask=np.zeros((80,80),bool)
    for y in range(2,78,10):
        for x in range(2,78,10):
            mask[y:y+3,x:x+3]=True
    result=simplify_mask(mask,{'width':80,'height':80},DEFAULT_CONFIG,upstream)
    assert result['status']=='redraw_required' and not result['polygons']
    assert result['source_pixels']>0 and result['iou'] is None


def test_instance_overlap_is_rejected_or_another_candidate_is_selected(upstream):
    mask=np.zeros((25,40),bool);mask[4:20,4:35]=True;mask[10,18]=False
    forbidden=np.zeros_like(mask);forbidden[10,18]=True
    result,actual=accepted(mask,upstream,forbidden=forbidden)
    assert not (actual&forbidden).any()
    # If every source pixel belongs to another instance, no candidate may pass.
    refused=simplify_mask(mask,{'width':40,'height':25},DEFAULT_CONFIG,upstream,mask)
    assert refused['status']=='redraw_required'


def test_empty_positive_is_not_a_negative(upstream):
    result=simplify_mask(np.zeros((14,20),bool),{'width':20,'height':14},DEFAULT_CONFIG,upstream)
    assert result['status']=='original_unresolved' and result['reason']=='original_empty_positive'
    assert result['iou'] is None and not result['polygons']


def test_native_bounds_and_per_polygon_complexity_cannot_be_silently_clipped(upstream):
    shape={'shape_type':'polygon','label':module.LABEL,'points':[[0,0],[40,0],[0,2]],
           'group_id':1,'flags':{'proposal_only':True,'mask_human_reviewed':False}}
    with pytest.raises(ValueError,match='unbounded'):
        grouped_pixels([shape],(25,40),upstream,DEFAULT_CONFIG)


def test_seeded_stratified_pilot_is_repeatable_and_never_uses_empty_positives():
    frames=[];targets={}
    for resolution in [(176,132),(224,172),(240,96),(352,264),(640,480)]:
        for i in range(40):
            fid=f'{resolution}_{i}'
            frames.append({'frame_id':fid,'width':resolution[0],'height':resolution[1]})
            targets[fid]=[{'frame_id':fid,'target_id':fid,'status':'candidate_needs_review'}]
    a=select_pilot(frames,targets,DEFAULT_CONFIG)
    assert a==select_pilot(frames,targets,DEFAULT_CONFIG) and len(a)==160
    assert all(sum(r['resolution']==list(size) for r in a)==32 for size in
               [(176,132),(224,172),(240,96),(352,264),(640,480)])


def fixture_argv(source,tmp_path,monkeypatch):
    monkeypatch.setattr(module,'check_space',lambda p:None)
    root,output=source
    config=dict(DEFAULT_CONFIG,pilot_targets_per_resolution=1)
    path=tmp_path/'config.json';path.write_bytes(encoded(config))
    return root,output,['--source',str(root),'--output',str(output),'--before',str(tmp_path/'none'),
                       '--config',str(path),'--workers','1']


def test_complete_export_verify_zip_portability_and_resume(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    main(argv)
    receipt=json.loads((output/'delivery_manifest.json').read_text())
    assert receipt['state']=='complete' and receipt['crc_passed'] and receipt['all_member_sha256_passed']
    assert receipt['summary']['frames']==3 and receipt['summary']['targets']==2
    assert receipt['summary']['confirmed_negative_frames']==1
    assert receipt['summary']['original_unresolved_targets']==1
    assert receipt['portable_load_save_documents']>=6
    for view in module.VIEWS:
        positive=json.loads((output/f'delivery/{view}/images/train/frame_0.json').read_text())
        assert positive['pallet_segmentation']['pixel_rotation_degrees']==180
        assert not positive['flags']['human_reviewed']
        assert positive['pallet_segmentation']['groups']
        unresolved=json.loads((output/f'delivery/{view}/images/test/frame_2.json').read_text())
        assert not unresolved['shapes'] and unresolved['flags']['redraw_required']
        assert unresolved['flags']['unresolved_positive'] and not unresolved['flags']['confirmed_negative']
        assert (output/f'delivery/redraw_previews/{view}/test/frame_2.png').exists()
    sha=receipt['archive_sha256']
    main(argv)
    assert json.loads((output/'delivery_manifest.json').read_text())['archive_sha256']==sha


def test_resume_and_package_preserve_human_changes_after_verify(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    main(argv+['--stage','pilot']);main(argv+['--stage','export']);main(argv+['--stage','verify'])
    path=output/'delivery/pallets/images/train/frame_0.json'
    data=json.loads(path.read_text());data['flags']['human_reviewed']=True
    path.write_bytes(encoded(data));human=path.read_bytes()
    with pytest.raises(ValueError,match='human edits'):
        main(argv+['--stage','export'])
    with pytest.raises(ValueError,match='human edits'):
        main(argv+['--stage','package'])
    assert path.read_bytes()==human


def test_frozen_input_change_refused_even_for_completed_export(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    main(argv+['--stage','pilot'])
    (root/'frames.jsonl').write_bytes(b'[]\n')
    with pytest.raises(ValueError,match='Frozen source'):
        main(argv+['--stage','export'])


def test_changed_configuration_cannot_resume_same_task(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    main(argv+['--stage','pilot'])
    config_path=Path(argv[argv.index('--config')+1]);config=json.loads(config_path.read_text())
    config['tolerances']=[0,.25,.5];config_path.write_bytes(encoded(config))
    with pytest.raises(ValueError,match='human edits'):
        main(argv+['--stage','export'])


def test_interrupted_frame_protects_existing_human_annotation(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    main(argv+['--stage','pilot'])
    path=output/'delivery/pallets/images/train/frame_0.json'
    protected_write(path,b'{"human_reviewed":true}')
    with pytest.raises(ValueError,match='human edits'):
        main(argv+['--stage','export'])
    assert path.read_bytes()==b'{"human_reviewed":true}'
