import hashlib
import json
from pathlib import Path
from types import SimpleNamespace

import cv2
import numpy as np
from PIL import Image
import pytest

import pallet.fork_face_anylabeling as module
from pallet.fork_face_anylabeling import (LABEL, completed, digest, encoded, grouped_pixels,
                                         main, mask_to_polygons, protected_write, rasterize)


def reconstructed(mask):
    polygons = mask_to_polygons(mask)
    result = np.zeros(mask.shape, bool)
    for points in polygons:
        assert len(points) >= 3 and len(set(map(tuple, points))) == len(points)
        result |= rasterize(points, mask.shape)
    assert np.array_equal(result, mask)
    return polygons


def test_holes_nested_islands_and_border_pixels_are_preserved():
    mask = np.ones((19, 27), bool)
    mask[3:16, 5:22] = False
    mask[7:12, 10:18] = True
    mask[8:11, 12:16] = False
    polygons = reconstructed(mask)
    assert len(polygons) > 1
    assert not any(rasterize(p, mask.shape)[4, 6] for p in polygons)


@pytest.mark.parametrize('size', [(1, 1), (1, 14), (15, 1), (3, 3), (15, 24)])
def test_singletons_lines_disconnected_pixels_and_random_masks(size):
    for seed in range(10):
        reconstructed(np.random.default_rng(seed).random(size) > .35)
    reconstructed(np.zeros(size, bool))
    reconstructed(np.ones(size, bool))


def test_disconnected_components_share_face_group_without_false_bridge():
    mask = np.zeros((12, 21), bool)
    mask[2:6, 2:6] = True
    mask[7:11, 14:20] = True
    polygons = mask_to_polygons(mask)
    shapes = [{'shape_type':'polygon','label':LABEL,'points':p,'group_id':9,
               'flags':{'proposal_only':True,'mask_human_reviewed':False}} for p in polygons]
    assert set(grouped_pixels(shapes, mask.shape)) == {9}
    assert np.array_equal(grouped_pixels(shapes, mask.shape)[9], mask)


def test_bounds_and_instance_flags_are_not_silently_corrected():
    shape = {'shape_type':'polygon','label':LABEL,'points':[[0, 0], [8, 0], [0, 2]],
             'group_id':1,'flags':{'proposal_only':True,'mask_human_reviewed':False}}
    with pytest.raises(ValueError, match='outside'):
        grouped_pixels([shape], (5, 8))
    shape['points'] = [[0, 0], [7, 0], [0, 2]]
    shape['flags']['mask_human_reviewed'] = True
    with pytest.raises(ValueError, match='promoted'):
        grouped_pixels([shape], (5, 8))


@pytest.fixture
def source(tmp_path, monkeypatch):
    monkeypatch.setattr(module, 'check_space', lambda p: None)
    root = tmp_path/'source'
    root.mkdir()
    frames, targets, faces = [], [], []
    for i, split in enumerate(['train','val','test']):
        key = f'frame_{i}'
        frame = {'frame_id':key,'frame_key':key,'split':split,'group_id':f'session_{i}',
            'width':20,'height':14,'image':f'images/{split}/{key}.png',
            'instances':f'instances/{split}/{key}.png','conflicts':f'conflicts/{split}/{key}.png',
            'task_hash':'parent_task','pixel_rotation_degrees':180 if i==0 else 0,
            'reconstructed_intensity':i==0,'frame_status':['candidate_needs_review','confirmed_negative','unresolved_positive'][i]}
        frames.append(frame)
        image_path = root/frame['image'];image_path.parent.mkdir(parents=True)
        image = np.arange(280,dtype=np.uint16).reshape(14,20).astype(np.uint8)
        Image.fromarray(image).save(image_path)
        mask = np.zeros((14,20),np.uint8)
        if i==0:
            mask[2:12,2:18] = 255;mask[4:10,6:14] = 0;mask[0,19] = 255
        for name, array in [('instances', (mask>0).astype(np.uint16)*7), ('conflicts', np.zeros_like(mask))]:
            path=root/frame[name];path.parent.mkdir(parents=True);Image.fromarray(array).save(path)
        if i!=1:
            target = {'frame_id':key,'target_id':key+'::box:0','box_index':0,'split':split,
                      'union_mask':f'masks/pallets/{split}/{key}.png',
                      'bbox':{'x':0,'y':0,'width':20,'height':14},'review_reasons':['forkability_not_confirmed'],
                      'status':'candidate_needs_review' if i==0 else 'unresolved_no_mask'}
            targets.append(target)
            path=root/target['union_mask'];path.parent.mkdir(parents=True);Image.fromarray(mask).save(path)
            if i==0:
                face = {'frame_id':key,'target_id':target['target_id'],'box_index':0,'split':split,
                        'face_id':7,'mask':f'masks/faces/{split}/{key}.png','status':'selected_candidate'}
                faces.append(face)
                path=root/face['mask'];path.parent.mkdir(parents=True);Image.fromarray(mask).save(path)
    for name,rows in [('frames',frames),('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':2}))
    hashes={str(p.relative_to(root)):digest(p) for p in root.rglob('*') if p.is_file()}
    (root/'export_manifest.json').write_bytes(encoded({'files':hashes,'summary':{'frames':3,'targets':2},'task_hash':'parent_task'}))
    return root, tmp_path/'output'


def test_complete_two_view_export_validation_zip_and_resume(source):
    root, output = source
    argv=['--source',str(root),'--output',str(output),'--workers','1']
    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']==receipt['summary']['unresolved_targets']==1
    assert receipt['validation']['polygon_mask_pixel_roundtrip']
    for view in ['faces','pallets']:
        positive=json.loads((output/f'delivery/{view}/images/train/frame_0.json').read_text())
        assert all(s['shape_type']=='polygon' for s in positive['shapes'])
        assert positive['pallet_segmentation']['pixel_rotation_degrees']==180
        assert positive['flags']['proposal_only'] and not positive['flags']['mask_human_reviewed']
        assert len({s['group_id'] for s in positive['shapes']})==1
        assert (root/'images/train/frame_0.png').read_bytes()==(output/f'delivery/{view}/images/train/frame_0.png').read_bytes()
        negative=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 negative['shapes'] and negative['flags']['confirmed_negative']
        assert not unresolved['shapes'] and unresolved['flags']['unresolved_positive'] and not unresolved['flags']['confirmed_negative']
        assert len(unresolved['pallet_segmentation']['parents'])==1
    archive=output/receipt['archive_name']; original=digest(archive)
    main(argv)
    assert original==digest(archive)


def test_resume_preserves_human_edits_and_refuses_changed_source(source):
    root, output=source
    argv=['--source',str(root),'--output',str(output),'--workers','1','--stage','export']
    main(argv)
    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)
    assert human==path.read_bytes()
    # Index changes are rejected even if the frame has no output yet.
    (root/'frames.jsonl').write_bytes(b'[]\n')
    with pytest.raises(ValueError,match='Frozen source changed'):
        main(argv)


def test_interrupted_uncommitted_frame_never_overwrites_json(source):
    root, output=source
    path=output/'delivery/pallets/images/train/frame_0.json'
    protected_write(path,b'{"human_reviewed":true}')
    with pytest.raises(ValueError,match='human edits'):
        main(['--source',str(root),'--output',str(output),'--workers','1','--stage','export'])
    assert path.read_bytes()==b'{"human_reviewed":true}'


def test_pinned_rasterizer_rejects_source_change(tmp_path):
    path=tmp_path/'shape.py'
    path.write_text('def shape_to_mask(img_shape, points, shape_type=None):\n return np.ones(img_shape, dtype=bool)\n')
    fn=module.load_upstream(path,digest(path))
    assert fn((2,3),[], 'polygon').all()
    with pytest.raises(ValueError,match='Pinned'):
        module.load_upstream(path,'0'*64)
