from copy import deepcopy
import json

import pytest

from pallet.pallet_description_round7_data import integrate,validate_required
from test_pallet_description_round5 import fixture


def test_partial_optional_diagnostics_keep_exact_baseline_without_fake_events():
    p,v,c=fixture();old=dict(p,source_revision=3,source_payload_sha256='prior',original_review_action='correct');base={'k':old};before=deepcopy(base)
    for reviews in ({},{'k':dict(v,action='draft')},{'k':dict(v,action='defer')}):
        result,changes=integrate(base,{'k':p},reviews,'existing',c,'binding')
        assert result==base==before and changes['retained_prior_baseline']==1 and changes['accepted_correct']==0


def test_correct_only_overlay_updates_round6_provenance_and_not_input():
    p,v,c=fixture();base={'k':dict(p,source_revision=2,source_payload_sha256='prior',original_review_action='correct')};before=deepcopy(base)
    result,changes=integrate(base,{'k':p},{'k':v},'existing',c,'binding')
    assert result['k']['geometry_source']=='latest_saved_human_correct_round6'
    assert result['k']['provenance_chain'][-1]['epoch']=='round6_training'
    assert changes['accepted_correct']==1 and changes['retained_prior_baseline']==0 and base==before
    assert result['k']['description']==v['description'] and not result['k']['ground_truth_eligible']


@pytest.mark.parametrize('action',[None,'draft','defer'])
def test_every_new_target_requires_correct(action):
    p,v,c=fixture()
    with pytest.raises(ValueError):integrate({}, {'k':p},{} if action is None else {'k':dict(v,action=action)},'new',c,'binding')


def test_required_gate_needs_individual_post_reopen_correct_not_batch():
    p,v,c=fixture();policy=dict(entries={'k':dict(tier='priority')});request=dict(targets={'k':dict(revision=1)});saved=dict(v,revision=2)
    for kind in ('human_batch_structure_text_confirmation','human_batch_structure_attributes_confirmation'):
        with pytest.raises(ValueError):validate_required({'k':p},{'k':saved},[('k',2,json.dumps(dict(saved,event_kind=kind)))],policy,request)
    assert validate_required({'k':p},{'k':saved},[('k',2,json.dumps(dict(saved,event_kind='human_joint_class_keypoints_description_review')))],policy,request)=={'k'}
    with pytest.raises(ValueError):validate_required({'k':p},{},[],policy,dict(targets={}))


def test_new_engines_do_not_change_old_training_or_prompt():
    from pallet import pallet_description_round7_mask as m,pallet_description_round7_vlm as v,pallet_description_round6_data as d
    assert m.ROOT==v.ROOT and m.ROOT.name=='pallet_description_round7_training_v1'
    assert m.implementation.PREVIOUS==v.implementation.PREVIOUS==d.ROOT
    assert 'round6_independent_branch_same_round7_latest_holdout_labels' in m.SOURCE
    assert 'from .pallet_description_round6_data import PROMPT as oldprompt' in v.SOURCE
    assert m.CONFIG['evaluation_epochs']==24 and m.CONFIG['full_pool_epochs']==20 and v.CONFIG['epochs']==2
    assert v.implementation.PROMPT==d.PROMPT


@pytest.mark.parametrize('mode',['new','existing'])
def test_next_ui_keeps_latest_shortcuts_terms_replacement_and_filters(mode):
    from pallet.pallet_description_round7_release import ui_assets,builder,REVIEW_SETS
    ui=ui_assets(mode);js=ui['review.js'];html=ui['page.html']
    assert "key==='s'&&!event.shiftKey?'correct'" in js
    assert 'structureTermsAdd' in html and 'structureReplace' in html and 'termsUpdatedDraft' in js
    assert js.count('pallet-description-round3-'+mode+'-v1:')==1 and 'pallet-description-round6-'+mode+'-v1:' not in js
    assert '第七轮' in html and 'Class13本次全组' not in html and '临时Class13待复查' not in html
    assert 'function class13Pending' not in js and 'imageCacheLimit=6' in js
    if mode=='existing':assert 'classRecordCounts' in html and 'function universalReviewFilters' in js
    module,source=builder()
    assert module.ROOT.name=='pallet_description_round7_training_v1' and module.REVIEW_SETS==REVIEW_SETS
    assert REVIEW_SETS['new']['port']==3422 and REVIEW_SETS['existing']['port']==3423


def test_next_ptunnel_binding_cannot_replace_round6_or_cloudflare():
    from scripts.serve_pallet_description_round7 import runtime
    row=dict(id=runtime.profile('new'),type='http',host='127.0.0.1',port=3422,target='127.0.0.1:3422',url='https://example.tunnel.phineas.top')
    assert runtime.validate_route(row,'new')==row and runtime.profile('new')=='pallet-description-round7-new'
    for change in ({'port':3420},{'target':'127.0.0.1:3420'},{'id':'pallet-description-round6-new'},{'url':'https://example.trycloudflare.com'}):
        with pytest.raises(ValueError):runtime.validate_route(dict(row,**change),'new')


def test_browser_suite_new_destinations_do_not_reopen_old_Class13_or_overwrite_old_tests():
    from scripts.check_pallet_description_round7_ui import keyboard_suite,replacement_suite,RELEASE,REVIEW_SETS
    keyboard,source=keyboard_suite();replacement,rsource=replacement_suite()
    assert keyboard.RELEASE==RELEASE and 'round7_v1' in str(RELEASE)
    assert replacement.REVIEW_SETS==REVIEW_SETS
    assert "if False:\n        require(chosen not in pending" in source
    assert 'from serve_pallet_review_triage import TriageHandler\nclass Quiet(TriageHandler):' in rsource
