from copy import deepcopy

import pytest

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


@pytest.mark.parametrize('action',[None,'draft','defer'])
def test_new_targets_cannot_accept_unsaved_or_draft(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')


@pytest.mark.parametrize('action',[None,'draft','defer'])
def test_optional_diagnostics_keep_exact_prior_baseline(action):
    p,v,c=fixture();base={'k':dict(p,source_revision=3,source_payload_sha256='prior',original_review_action='correct')};before=deepcopy(base)
    result,changes=integrate(base,{'k':p},{} if action is None else {'k':dict(v,action=action)},'existing',c,'binding')
    assert result==base==before and changes['accepted_correct']==0 and changes['retained_prior_baseline']==1


def test_latest_correct_overlays_once_with_round7_provenance():
    p,v,c=fixture();base={'k':dict(p,source_revision=3,source_payload_sha256='prior',original_review_action='correct')};before=deepcopy(base)
    result,changes=integrate(base,{'k':p},{'k':v},'existing',c,'binding')
    assert base==before and result['k']['description']==v['description'] and result['k']['geometry_source']=='latest_saved_human_correct_round7'
    assert result['k']['provenance_chain'][-1]['epoch']=='round7_training' and len(result['k']['provenance_chain'])==1
    assert changes['accepted_correct']==1 and not result['k']['ground_truth_eligible'] and not result['k']['robot_command_eligible']


@pytest.mark.parametrize('change',[{'source_binding':'stale'},{'binding':'stale'},{'polygon':[[1,1],[2,1],[1,2]]},{'class_K_matches':False}])
def test_completed_binding_and_strictK_still_enforced(change):
    p,v,c=fixture()
    with pytest.raises(ValueError):integrate({}, {'k':p},{'k':dict(v,**change)},'new',c,'binding')


def test_required_policy_uses_priority_and_fixed_audit_not_diagnostics():
    props={k:{} for k in ('p','a','d')};policy=dict(entries={'p':dict(tier='priority'),'a':dict(tier='audit'),'d':dict(tier='diagnostic')},actual_audit_count=1)
    reviews={k:dict(action='correct') for k in ('p','a')}
    assert validate_required(props,reviews,[],policy)=={'p','a'}
    with pytest.raises(ValueError):validate_required(props,dict(reviews,a=dict(action='draft')),[],policy)
    with pytest.raises(ValueError):validate_required(props,reviews,[],dict(policy,actual_audit_count=50))


def test_independent_new_engines_and_previous_comparison():
    from pallet import pallet_description_round8_mask as m,pallet_description_round8_vlm as v,pallet_description_round7_data as previous
    assert m.ROOT==v.ROOT and m.ROOT.name=='pallet_description_round8_training_v1'
    assert m.implementation.PREVIOUS==v.implementation.PREVIOUS==previous.ROOT
    assert 'round7_independent_branch_same_round8_latest_holdout_labels' in m.SOURCE
    assert 'from .pallet_description_round7_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==previous.PROMPT


@pytest.mark.parametrize('mode',['new','existing'])
def test_round8_UI_namespaces_shortcuts_filters_and_ports(mode):
    from pallet.pallet_description_round8_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 and 'structureReplace' in html and 'structureTermsDelete' in html
    assert js.count('pallet-description-round3-'+mode+'-v1:')==1 and '第八轮' in html and '第七轮' 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_round8_training_v1'
    assert REVIEW_SETS['new']['port']==3424 and REVIEW_SETS['existing']['port']==3425


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


def test_new_GUI_and_audit_destinations_do_not_rewrite_old_artifacts():
    from scripts.check_pallet_description_round8_ui import keyboard_suite,replacement_suite,RELEASE,REVIEW_SETS
    from scripts.finalize_pallet_description_round8 import implementation
    keyboard,_=keyboard_suite();replacement,_=replacement_suite()
    assert keyboard.RELEASE==RELEASE and 'round8_v1' in str(RELEASE) and replacement.REVIEW_SETS==REVIEW_SETS
    assert implementation.ROOT.name=='pallet_description_round8_training_v1' and implementation.PREVIOUS.name=='pallet_description_round7_training_v1'
