import copy
import json
from pathlib import Path
import shutil
import zipfile

import numpy as np
from PIL import Image
import pytest

from pallet.cluster_annotation_rectangles import main, rectangle_document
from pallet.fork_face_anylabeling import digest, encoded


def frame_document():
    boxes = [{'x': 2.25, 'y': 3.5, 'width': 11.1, 'height': 8.2},
             {'x': 13.4, 'y': 2.1, 'width': 5.2, 'height': 7.6}]
    frame = {'frame_id': 'frame', 'width': 20, 'height': 14, 'boxes': boxes,
             'ignore_regions': [], 'image': 'images/train/frame.png', 'split': 'train', 'group_id': 'g'}
    doc = {'version': '0.4.43', 'flags': {'human_reviewed': True, 'proposal_only': False},
           'imagePath': 'frame.png', 'imageData': None, 'imageWidth': 20, 'imageHeight': 14,
           'text': '', 'shapes': [{'label': 'pallet', 'shape_type': 'rectangle',
                'points': [[b['x'], b['y']], [b['x']+b['width'], b['y']+b['height']]],
                'group_id': None, 'text': '', 'flags': {'human_reviewed': True, 'proposal_only': False}}
                for b in boxes],
           'pallet_export': {'frame_id': 'frame', 'pixel_rotation_degrees': 180, 'reconstructed_intensity': True}}
    selected = {'appearance_class': 'A00', 'frame_id': 'frame', 'target_id': 'frame::box:0000',
                'box_index': 0, 'bbox': boxes[0], 'split': 'train', 'group_id': 'g'}
    return frame, doc, selected


def test_original_float_rectangles_other_pallets_and_detection_review_preserved():
    frame, doc, selected = frame_document()
    before = copy.deepcopy(doc)
    actual = rectangle_document(doc, frame, selected)
    assert doc == before
    assert actual['shapes'] == before['shapes'] and len(actual['shapes']) == 2
    assert actual['pallet_export']['pixel_rotation_degrees'] == 180
    assert actual['flags']['human_reviewed'] and not actual['flags']['mask_human_reviewed']
    assert not actual['flags']['segmentation_training_eligible']
    assert actual['pallet_annotation_task']['selected_bbox'] == selected['bbox']
    assert actual['pallet_annotation_task']['polygon_annotations'] == 0


def test_source_polygon_or_mismatched_rectangle_rejected():
    frame, doc, selected = frame_document()
    doc['shapes'][0]['shape_type'] = 'polygon'
    with pytest.raises(ValueError, match='valid native rectangle'):
        rectangle_document(doc, frame, selected)
    frame, doc, selected = frame_document()
    doc['shapes'][1]['points'][0][0] += .1
    with pytest.raises(ValueError, match='differ from formal'):
        rectangle_document(doc, frame, selected)


@pytest.fixture
def flat_input(tmp_path):
    dataset, seed, output = tmp_path/'dataset', tmp_path/'seed', tmp_path/'output'
    frame, original, selected = frame_document()
    (dataset/'images/train').mkdir(parents=True)
    (dataset/'annotations').mkdir()
    Image.fromarray(np.arange(280, dtype=np.uint16).reshape(14, 20).astype(np.uint8)).save(dataset/frame['image'])
    annotation = Path(frame['image']).with_suffix('.json')
    (dataset/annotation).write_bytes(encoded(original))
    (dataset/'annotations/frames.jsonl').write_bytes(encoded(frame))
    formal = {'binding': {'dataset': str(dataset)}, 'protected_files':
              {str(annotation): digest(dataset/annotation),
               'annotations/frames.jsonl': digest(dataset/'annotations/frames.jsonl')}}
    formal_path = tmp_path/'formal.json'; formal_path.write_bytes(encoded(formal))
    delivery = seed/'delivery'; (delivery/'A00/images').mkdir(parents=True)
    (delivery/'source').mkdir()
    shutil.copyfile(dataset/frame['image'], delivery/'A00/images/frame.png')
    (delivery/'selection.jsonl').write_bytes(encoded(selected))
    (delivery/'manifest.json').write_bytes(encoded({'binding': {}}))
    upstream = Path('outputs/pallet_cluster_annotation_seed_v1/delivery/source/anylabeling_label_file.py')
    shutil.copyfile(upstream, delivery/'source/anylabeling_label_file.py')
    registry = {str(p.relative_to(delivery)): digest(p) for p in delivery.rglob('*') if p.is_file()}
    (delivery/'verified_assets.json').write_bytes(encoded({'files': registry}))
    archive = seed/'seed.zip'
    with zipfile.ZipFile(archive, 'w') as z:
        z.writestr('frozen', 'seed')
    (seed/'delivery_manifest.json').write_bytes(encoded({'archive_name': archive.name,
        'archive_sha256': digest(archive),
        'validation': {'verified_assets_sha256': digest(delivery/'verified_assets.json')}}))
    args = ['--seed-source', str(seed), '--formal-manifest', str(formal_path), '--output', str(output)]
    return dataset, seed, output, args


def test_flat_delivery_zip_official_format_and_repeat(flat_input):
    dataset, seed, output, args = flat_input
    main(args)
    receipt = json.loads((output/'delivery_manifest.json').read_text())
    assert receipt['summary']['frames'] == 1 and receipt['summary']['original_pallet_rectangles'] == 2
    assert receipt['summary']['polygon_annotations'] == 0
    assert receipt['crc_passed'] and receipt['all_member_sha256_passed'] and receipt['flat_archive']
    assert receipt['portable_load_save_documents'] == 1
    doc = json.loads((output/'delivery/frame.json').read_text())
    original = json.loads((dataset/'images/train/frame.json').read_text())
    assert doc['shapes'] == original['shapes']
    assert (output/'delivery/frame.png').read_bytes() == (dataset/'images/train/frame.png').read_bytes()
    assert not any(p.is_dir() for p in (output/'delivery').iterdir())
    with zipfile.ZipFile(output/receipt['archive_name']) as z:
        assert not any('/' in name for name in z.namelist())
        assert 'frame.png' in z.namelist() and 'frame.json' in z.namelist()
    sha = receipt['archive_sha256']; main(args)
    assert digest(output/receipt['archive_name']) == sha


@pytest.mark.parametrize('stage', ['export', 'verify', 'package'])
def test_flat_human_changes_preserved(flat_input, stage):
    _, _, output, args = flat_input
    main(args)
    path = output/'delivery/frame.json'
    doc = json.loads(path.read_text()); doc['shapes'].append({'label': 'pallet_fork_face', 'shape_type': 'polygon'})
    path.write_bytes(encoded(doc)); modified = path.read_bytes()
    with pytest.raises(ValueError, match='human edits'):
        main(args+['--stage', stage])
    assert path.read_bytes() == modified


def test_changed_source_rectangle_refused(flat_input):
    dataset, _, output, args = flat_input
    main(args+['--stage', 'export'])
    path = dataset/'images/train/frame.json'; doc = json.loads(path.read_text())
    doc['shapes'][0]['points'][0][0] = 9; path.write_bytes(encoded(doc))
    with pytest.raises(ValueError, match='Frozen source changed'):
        main(args+['--stage', 'export'])
