"""Publication-specific gallery bindings and collision-free historical rendering."""
import copy
import json

import pytest

from pallet.cluster_targets import digest
from pallet.mask_template_continue import sha
from pallet.mask_template_refined_next import (CLASSES, EDITOR_VERSION,
    gallery_templates, preserve_parent_assets, rendering_inventory, write_jsonl)


@pytest.fixture
def gallery_fixture(tmp_path):
    parent = tmp_path/'parent'; historical = tmp_path/'historical'
    (parent/'images').mkdir(parents=True); historical.mkdir()
    rows = {}; previous = []; reviews = {}
    polygon = [[1,1],[20,1],[20,10],[15,10],[15,5],[5,5],[5,10],[1,10]]
    for i in range(97):
        key = f'{i:024x}'
        row = dict(target_key=key, frame_id=f'frame-{i}', split='train', box_index=0,
            bbox=dict(x=1,y=1,width=19,height=9),size=[24,16],source_pcd_sha256='pcd', final_class_id=CLASSES[i%5])
        rows[key] = row
        (parent/'images'/f'{key}.png').write_bytes(b'image')
        p = dict(target_key=key,source=row,class_id=row['final_class_id'],formal_manifest_sha256='formal')
        previous.append(p)
        identity = {k:row[k] for k in ('target_key','frame_id','split','box_index','bbox','size','source_pcd_sha256')}
        identity.update(formal_manifest_sha256='formal',image_sha256=digest(parent/'images'/f'{key}.png'))
        reviews[key] = dict(target_key=key,source=identity,source_binding=sha(identity),base_proposal_id=sha(p),
            revision=7,polygon=copy.deepcopy(polygon),vertex_count=8,event_kind='human_mask_gallery_revision',
            human_edited=True,proposal_publication=3 if i<56 else 4)
    paths = {3:historical,4:parent}
    for version,path in paths.items():
        write_jsonl(path/'proposals.jsonl',previous[:56] if version==3 else previous)
        proposals_sha = digest(path/'proposals.jsonl')
        (path/'manifest.json').write_text(json.dumps(dict(publication_version=version,
            formal_manifest_sha256='formal',proposals_sha256=proposals_sha)))
        (path/'verification.json').write_text(json.dumps(dict(state='passed',proposals_sha256=proposals_sha)))
        binding = sha(dict(formal='formal',proposals=proposals_sha,editor_version=EDITOR_VERSION))
        for r in reviews.values():
            if r['proposal_publication']==version:
                r['binding'] = binding
    return parent,rows,previous,reviews,paths


def make_templates(fixture, events=None, pose=None):
    parent,rows,previous,reviews,paths = fixture
    return gallery_templates(previous,reviews,list(reviews.values()) if events is None else events,
        {} if pose is None else pose,rows,parent,'formal','snapshot',paths)


def test_mixed_historical_publications_and_independent_pose_revision(gallery_fixture):
    _,rows,_,reviews,_ = gallery_fixture
    first,second = list(rows)[:2]
    pose = dict(revision=19,polygon=[[0,0],[1,0],[1,1],[0,1]])
    templates = make_templates(gallery_fixture,pose={first:pose})
    assert len(templates)==97
    assert templates[first]['revision']==19
    assert templates[first]['current_payload_sha256']==sha(pose)
    assert templates[first]['human_polygon_revision']==7
    assert templates[second]['revision']==0 and templates[second]['current_payload_sha256'] is None
    assert templates[first]['gallery_review']==dict(target_key=first,revision=7,payload_sha256=sha(reviews[first]),
        source_binding=reviews[first]['source_binding'],polygon_sha256=sha(reviews[first]['polygon']),snapshot_sha256='snapshot')
    assert {r['proposal_publication'] for r in reviews.values()}=={3,4}


@pytest.mark.parametrize('attack', ['source','binding','proposal','latest','vertices',
    'publication','wrong_publication_binding','absent_in_publication','duplicate_revision','missing_edit','not_human'])
def test_reject_invalid_or_unsaved_seeds(gallery_fixture, attack):
    _,_,_,reviews,_ = gallery_fixture
    events = copy.deepcopy(list(reviews.values())); first = next(iter(reviews)); r = reviews[first]
    if attack=='source': r['source']['frame_id']='other'
    elif attack=='binding': r['source_binding']='invalid'
    elif attack=='proposal': r['base_proposal_id']='invalid'
    elif attack=='latest': events.append(dict(r,revision=8))
    elif attack=='vertices': r['polygon']=r['polygon'][:4]
    elif attack=='publication': r['proposal_publication']=99
    elif attack=='wrong_publication_binding': r['binding']=list(reviews.values())[-1]['binding']
    elif attack=='absent_in_publication':
        r=list(reviews.values())[-1]
        r['proposal_publication']=3; r['binding']=reviews[first]['binding']
        events=copy.deepcopy(list(reviews.values()))
    elif attack=='duplicate_revision': events.append(copy.deepcopy(r))
    elif attack=='missing_edit': del reviews[first]
    else: r['human_edited']=False
    with pytest.raises(ValueError):
        make_templates(gallery_fixture,events)


def test_reject_tampered_frozen_publication(gallery_fixture):
    *_,paths = gallery_fixture
    with (paths[3]/'proposals.jsonl').open('a') as f:
        f.write('{}\n')
    with pytest.raises(ValueError,match='Historical publication'):
        make_templates(gallery_fixture)


def test_historical_and_refined_assets_keep_separate_bytes(tmp_path):
    parent = tmp_path/'parent'; out = tmp_path/'out'
    for root in (parent,out):
        for name in ('cases','images','masks','labelme','templates'):
            (root/name).mkdir(parents=True)
    for name in ('templates','labelme'):
        (parent/'refined'/name).mkdir(parents=True)
    for folder,ext in (('cases','png'),('images','png'),('masks','png'),('labelme','json')):
        (parent/folder/f'old.{ext}').write_bytes(b'historical-asset')
    (parent/'templates/shared.json').write_bytes(b'historical')
    (parent/'refined/templates/shared.json').write_bytes(b'prior-refined')
    (parent/'refined/labelme/shared.json').write_bytes(b'prior-refined-labelme')
    (out/'templates/shared.json').write_bytes(b'latest-generation')
    hashes = preserve_parent_assets(parent,out,[dict(target_key='old')])
    assert (out/'generation/templates/shared.json').read_bytes()==b'latest-generation'
    assert (out/'templates/shared.json').read_bytes()==b'historical'
    assert (out/'refined/templates/shared.json').read_bytes()==b'prior-refined'
    assert (out/'refined/labelme/shared.json').read_bytes()==b'prior-refined-labelme'
    assert all(digest(out/path)==value for path,value in hashes.items())


def test_mixed_inventory_keeps_prior_rendering_identities():
    original = dict(row=dict(target_key='shared'),polygon='historical',rendering_id='historical:shared')
    refined = dict(row=dict(target_key='shared'),polygon='refined',rendering_id='refined:shared')
    parent = dict(templates=[original,refined],rendering_by_target={'old':'historical:shared','recent':'refined:shared'})
    before = copy.deepcopy(parent)
    templates = {'shared':dict(row=dict(target_key='shared'),polygon='latest')}
    combined = [dict(target_key=k,template=dict(target_key='shared')) for k in ('old','recent','new')]
    inventory = rendering_inventory(parent,templates,combined,{'new'})
    assert parent==before
    assert inventory['templates'][:2]==parent['templates']
    assert inventory['rendering_by_target']==dict(old='historical:shared',recent='refined:shared',new='generation:shared')
    assert inventory['historical_templates']==2 and inventory['gallery_human_templates']==1
    assert inventory['conflicting_template_keys']==['shared']
