import json
from pathlib import Path

import numpy as np
import pytest

import pallet.fork_face_enclosure as module
from pallet.fork_face_enclosure import DEFAULT_CONFIG,enclose_mask,filled_evidence,main
from pallet.fork_face_anylabeling import encoded,load_upstream
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 assert_cover(mask,upstream):
    result=enclose_mask(mask,DEFAULT_CONFIG,upstream)
    assert result['status']=='enclosure_ready' and len(result['polygons'])==1
    assert 3<=len(result['polygons'][0])<=24
    actual=upstream(mask.shape,result['polygons'][0],'polygon')
    filled,_=filled_evidence(mask)
    assert not (filled&~actual).any() and result['source_coverage']==1
    assert result['deleted_pixels']==0
    assert not filled_evidence(actual)[1].any()
    return result,actual


def test_internal_holes_and_missing_measurements_filled_without_iou_gate(upstream):
    mask=np.zeros((40,70),bool);mask[3:37,3:67]=True;mask[6:34,6:64]=False
    result,actual=assert_cover(mask,upstream)
    assert actual[6:34,6:64].all() and result['filled_original_hole_pixels']==28*58
    assert result['iou']<.4 and result['added_pixels']>result['source_pixels']


def test_outer_concavity_retained_and_area_smaller_than_convex_hull(upstream):
    mask=np.zeros((40,55),bool);mask[4:35,4:12]=True;mask[27:35,4:48]=True;mask[4:35,40:48]=True
    result,actual=assert_cover(mask,upstream)
    assert not actual[8:24,16:36].any()
    assert result['output_pixels']<44*31
    assert result['parameters']['method']=='concave_cover'


def test_fragments_unified_into_one_closed_outline_and_all_points_kept(upstream):
    mask=np.zeros((38,80),bool);mask[4:15,4:22]=True;mask[24:34,55:74]=True
    mask[2,76]=True;mask[35,2]=True
    result,actual=assert_cover(mask,upstream)
    assert actual[2,76] and actual[35,2]
    assert result['polygon_count']==1


@pytest.mark.parametrize('size',[(1,1),(1,33),(27,1),(5,7),(90,140)])
def test_border_singleton_thin_structures_and_small_targets(size,upstream):
    result,actual=assert_cover(np.ones(size,bool),upstream)
    assert actual.all()
    assert all(0<=x<size[1] and 0<=y<size[0] for p in result['polygons'] for x,y in p)


def test_many_random_holes_and_thin_branches_cover_all_source_pixels(upstream):
    mask=np.random.default_rng(42).random((25,50))>.6
    mask[0,:]=True;mask[-1,::2]=True;mask[:,0]=True
    result,actual=assert_cover(mask,upstream)
    assert result['source_coverage']==1 and result['vertex_count']<=24


def test_empty_positive_never_invented_as_negative(upstream):
    result=enclose_mask(np.zeros((16,24),bool),DEFAULT_CONFIG,upstream)
    assert result['status']=='original_unresolved' and not result['polygons'] and result['iou'] is None


def test_native_fill_area_includes_scanline_pixel_beyond_local_bounds(upstream):
    points=[[0,0],[1,0],[0,1],[1,1],[1,2],[2,2],[3,2],[4,2],[1,3],[3,3],[4,3],
        [1,4],[3,4],[4,4],[3,5],[4,5],[16,8],[15,9],[16,9],[17,9],[19,9],
        [18,10],[19,10],[18,11],[19,11],[4,12],[4,13],[5,13],[19,13],[20,13],
        [5,14],[6,14],[7,14],[18,14],[19,14],[20,14],[5,15],[6,15],[8,15],
        [18,15],[19,15],[20,17],[46,17],[42,19],[43,19],[45,21],[41,22],[45,23],[45,24]]
    mask=np.zeros((172,224),bool)
    for x,y in points:mask[y+116,x+53]=True
    result,actual=assert_cover(mask,upstream)
    assert result['output_pixels']==int(actual.sum())
    assert result['added_pixels']==int((actual&~mask).sum())
    assert result['iou']==mask.sum()/actual.sum()


def fixture_argv(source,tmp_path,monkeypatch):
    monkeypatch.setattr(module,'check_space',lambda p:None)
    root,output=source
    config={**DEFAULT_CONFIG,'pilot_targets_per_resolution':1}
    path=tmp_path/'enclosure.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_actual_export_load_save_verification_zip_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['validation']['original_source_coverage_100_percent']
    for view in ['faces','pallets']:
        doc=json.loads((output/f'delivery/{view}/images/train/frame_0.json').read_text())
        assert len(doc['shapes'])==1
        assert doc['pallet_segmentation']['internal_holes_deliberately_filled']
        assert not doc['pallet_segmentation']['iou_is_acceptance_condition']
        assert doc['pallet_segmentation']['pixel_rotation_degrees']==180
        neg=json.loads((output/f'delivery/{view}/images/val/frame_1.json').read_text())
        unresolved=json.loads((output/f'delivery/{view}/images/test/frame_2.json').read_text())
        assert not neg['shapes'] and neg['flags']['confirmed_negative']
        assert not unresolved['shapes'] and unresolved['flags']['unresolved_positive']
        assert not unresolved['flags']['confirmed_negative'] and unresolved['flags']['redraw_required']
    sha=receipt['archive_sha256'];main(argv)
    assert json.loads((output/'delivery_manifest.json').read_text())['archive_sha256']==sha


def test_modified_human_json_protected_during_resume_and_package(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    for stage in ['pilot','export','verify']:main(argv+['--stage',stage])
    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()
    for stage in ['export','package']:
        with pytest.raises(ValueError,match='human edits'):main(argv+['--stage',stage])
    assert path.read_bytes()==human


def test_changed_frozen_mask_or_config_refuses_resume(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    main(argv+['--stage','pilot'])
    mask=next((root/'masks/pallets/train').rglob('*.png'));mask.write_bytes(b'broken')
    with pytest.raises(ValueError,match='Frozen source'):main(argv+['--stage','pilot'])


def test_simplification_entry_alias_uses_new_user_rule(source,tmp_path,monkeypatch):
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    from pallet.fork_face_simplify import main as alias
    alias(['--cover-mask',*argv,'--stage','pilot'])
    report=json.loads((output/'pilot_report.json').read_text())
    assert report['iou_acceptance_threshold'] is None and report['hull']=='concave'


def test_enclosing_different_instances_keeps_identity_and_reports_overlap(source,tmp_path,monkeypatch):
    from PIL import Image
    from pallet.fork_face_anylabeling import digest
    root,output,argv=fixture_argv(source,tmp_path,monkeypatch)
    targets=[json.loads(l) for l in (root/'targets.jsonl').read_bytes().splitlines()]
    faces=[json.loads(l) for l in (root/'faces.jsonl').read_bytes().splitlines()]
    second={**targets[0],'target_id':'frame_0::box:1','box_index':1,
            'union_mask':'masks/pallets/train/second.png','bbox':{'x':6,'y':4,'width':8,'height':6}}
    mask=np.zeros((14,20),np.uint8);mask[4:10,6:14]=255
    Image.fromarray(mask).save(root/second['union_mask'])
    second_face={**faces[0],'target_id':second['target_id'],'box_index':1,'face_id':8,
                 'mask':'masks/faces/train/second.png'}
    Image.fromarray(mask).save(root/second_face['mask'])
    targets.append(second);faces.append(second_face)
    for name,rows in [('targets',targets),('faces',faces)]:
        (root/(name+'.jsonl')).write_bytes(b''.join(encoded(r) for r in rows))
    (root/'summary.json').write_bytes(encoded({'frames':3,'targets':3}))
    hashes={str(p.relative_to(root)):digest(p) for p in root.rglob('*') if p.is_file() and p.name!='export_manifest.json'}
    (root/'export_manifest.json').write_bytes(encoded({'files':hashes,'summary':{'frames':3,'targets':3},'task_hash':'parent_task'}))
    main(argv)
    for view in ['faces','pallets']:
        doc=json.loads((output/f'delivery/{view}/images/train/frame_0.json').read_text())
        assert len(doc['shapes'])==2 and len({s['group_id'] for s in doc['shapes']})==2
        assert doc['flags']['enclosure_overlap'] and doc['pallet_segmentation']['overlap_pixels']>0
        assert all(g['enclosure_overlap_needs_review'] for g in doc['pallet_segmentation']['groups'])
