from copy import deepcopy

import pytest

from pallet.pallet_description_round6_data import integrate
from test_pallet_description_round5 import fixture


def test_completed_overlay_has_round5_provenance_and_no_duplicates():
    p,v,classes=fixture();old={**p,'source_revision':1,'original_review_action':'draft','source_payload_sha256':'old'};base={'k':old};before=deepcopy(base)
    result,changes=integrate(base,{'k':p},{'k':v},'existing',classes,'binding')
    assert len(result)==1 and base==before and result['k']['source_payload_sha256']!='old'
    assert result['k']['provenance_chain']==[dict(epoch='round5_training',revision=1,action='draft',source_payload_sha256='old')]
    assert result['k']['geometry_source']=='latest_saved_human_correct_round5' and changes['observation_changed']==0


@pytest.mark.parametrize('action',['draft','defer'])
def test_no_fabricated_completion_acceptance(action):
    p,v,classes=fixture()
    with pytest.raises(ValueError):integrate({}, {'k':p},{'k':dict(v,action=action)},'new',classes,'binding')


def test_new_unique_only_and_existing_must_already_exist():
    p,v,classes=fixture();result,_=integrate({}, {'k':p},{'k':v},'new',classes,'binding')
    assert len(result)==1
    with pytest.raises(ValueError):integrate(result,{'k':p},{'k':v},'new',classes,'binding')
    with pytest.raises(ValueError):integrate({}, {'k':p},{'k':v},'existing',classes,'binding')
    with pytest.raises(ValueError):integrate({}, {'k':p},{'k':v},'invalid',classes,'binding')


def test_strict_K_binding_source_and_full_coverage():
    p,v,classes=fixture()
    for change in ({'source_binding':'stale'},{'binding':'old'},{'polygon':v['polygon'][:3]},{'source':{'size':[20,20]}},{'class_K_matches':False}):
        with pytest.raises(ValueError):integrate({}, {'k':p},{'k':dict(v,**change)},'new',classes,'binding')
    with pytest.raises(ValueError):integrate({}, {'k':p},{},'new',classes,'binding')


def test_completed_description_text_and_empty_anomaly_not_rewritten():
    p,v,classes=fixture();v=deepcopy(v);v['description']['text']='木质，独有项，木质';before=deepcopy(v)
    result,_=integrate({}, {'k':p},{'k':v},'new',classes,'binding')
    assert v==before and result['k']['description']==v['description']
    assert not result['k']['ground_truth_eligible'] and not result['k']['robot_command_eligible']


def test_training_adapters_are_new_instances_and_use_matching_previous_prompt():
    from pallet import pallet_description_round6_mask as mask,pallet_description_round6_vlm as vlm
    from pallet import pallet_description_round5_data as old
    assert mask.ROOT==vlm.ROOT and 'round6_training' in str(mask.ROOT)
    assert mask.learning.ROOT==mask.ROOT and vlm.learning.ROOT==vlm.ROOT
    assert mask.implementation.PREVIOUS==vlm.implementation.PREVIOUS==old.ROOT
    assert 'round5_independent_branch_same_round6_latest_holdout_labels' in mask.SOURCE
    assert 'from .pallet_description_round5_data import PROMPT as oldprompt' in vlm.SOURCE
    assert vlm.implementation.PROMPT==old.PROMPT and vlm.CONFIG['observation_always_JSON_string']


def test_round6_missing_observation_has_quotes_not_normal_semantic_labels():
    from pallet.pallet_description_round6_vlm import format_target,mask_spans,answer_spans
    r=dict(target={'支腿':3,'横梁':2,'材质':'木质','结构':'人工原文','观察':None},supervised_fields={k:k!='观察' for k in ('支腿','横梁','材质','结构','观察')})
    before=deepcopy(r);target=format_target(r);answer,spans=answer_spans(target)
    assert target['观察']=='' and answer[slice(*spans['观察'])]=='""' and not mask_spans(r,spans) and r==before


def test_next_UI_keeps_terms_and_fast_navigation_without_old_namespace():
    from pallet.pallet_description_round6_release import ui_assets,builder
    ui=ui_assets('new');js=ui['review.js']
    assert '第六轮' in ui['page.html'] and 'structureTermsDelete' in ui['page.html'] and 'VLM材质一致率较上轮回退' in ui['page.html']
    assert 'imageCacheLimit=6' in js and 'Promise.all([request(' in js and 'termsUpdatedDraft' in js
    assert js.count('pallet-description-round3-new-v1:')==1 and 'pallet-description-round5-new-v1:' not in js
    module,source=builder()
    assert module.ROOT.name=='pallet_description_round6_training_v1' and module.REVIEW_SETS['new']['port']==3420
    assert 'structure_terms_batch_enabled=True' in source and 'round6-semantic-audit' in source


def test_next_profiles_are_independent_and_validate_exact_binding():
    from scripts.serve_pallet_description_round6 import validate_route,profile
    row=dict(id=profile('new'),type='http',host='127.0.0.1',port=3420,target='127.0.0.1:3420',url='https://example.tunnel.phineas.top')
    assert validate_route(row,'new')==row and profile('new')=='pallet-description-round6-new'
    for change in ({'id':'pallet-description-round5-new'},{'port':3418},{'target':'127.0.0.1:3418'},{'host':'0.0.0.0'},{'url':'https://example.trycloudflare.com'},{'url':'https://user:pass@example.tunnel.phineas.top'},{'url':'https://example.tunnel.phineas.top/path'}):
        with pytest.raises(ValueError):validate_route(dict(row,**change),'new')


def test_new_serving_rebind_keeps_completed_source_sets_immutable():
    from pallet import pallet_description_review as review,pallet_description_round6_data as data
    from pallet.pallet_description_round6_release import bind_review_sets
    before=deepcopy(data.SOURCE_SETS);original=review.SETS
    try:
        bind_review_sets()
        assert data.SOURCE_SETS==before and all('round5_' in str(s['root']) for s in data.SOURCE_SETS.values())
        assert all('round6_' in str(s['root']) for s in review.SETS.values())
    finally:review.SETS=original


def test_new_ui_builder_reinserts_evidence_only_once():
    from pallet.pallet_description_round6_release import ui_assets
    ui=ui_assets('new');js=ui['review.js']
    assert "+'\\n上轮描述基线：'" not in js
    assert "$('modelInfo').textContent=`" in js
    assert js.count("+'\\n当前规则：异常描述为空按正常处理。';")==1


def test_dynamic_suite_never_retains_a_frozen_round5_output_destination():
    from pathlib import Path
    from scripts.check_pallet_description_round6_ui import load_terms_suite,RELEASE,REVIEW_SETS
    source=(Path(__file__).resolve().parents[1]/'scripts/check_pallet_description_terms.py').read_text().replace('round5','round6')
    module=load_terms_suite(source)
    assert module.RELEASE==module.BASE==RELEASE and module.REVIEW_SETS==REVIEW_SETS
    assert all('round6_' in str(s['root']) for s in module.REVIEW_SETS.values())


def test_provision_does_not_expose_an_unrelated_listener(monkeypatch):
    from types import SimpleNamespace
    from scripts import serve_pallet_description_round6 as service
    monkeypatch.setattr(service,'configure',lambda mode:None)
    monkeypatch.setattr(service,'PTUNNEL',SimpleNamespace(is_file=lambda:True))
    monkeypatch.setattr(service,'port_available',lambda port:False)
    monkeypatch.setattr(service,'healthy',lambda mode:False)
    monkeypatch.setattr(service,'profiles',lambda:(_ for _ in ()).throw(AssertionError('must reject before tunnel inventory/create')))
    with pytest.raises(ValueError,match='unrelated service'):service.provision('new')
