"""Full proven GUI/terms suite, newly mapped actual classes and fast D/A timing."""
from collections import Counter
from pathlib import Path
import sys
import types

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.cluster_targets import digest
from pallet.mask_model_training_data import read,write,jsonl,require
from pallet.pallet_description_round6_data import ROOT,binding_guard,sources_current
from pallet.pallet_description_round6_release import REVIEW_SETS,RELEASE,bind_review_sets
from pallet.pallet_description_simple import ROOT as SIMPLE_ROOT
from serve_pallet_description_round6 import CODE


def adapt_sources(mode):
    folder=RELEASE/mode;adapted=folder/'adapted_test_code';adapted.mkdir(mode=0o700,exist_ok=True)
    counts=Counter(p['class_id'] for p in jsonl(REVIEW_SETS[mode]['root']/'proposals.jsonl'))
    available=sorted([c for c,n in counts.items() if n>=10],key=lambda c:(-counts[c],c));require(len(available)>=4,'Need four actual ten-item class panels for the inherited full suite')
    mapping=dict(zip((1,2,3,4),available[:4]))
    for name in ('check_pallet_description_simple','check_pallet_description_single','check_pallet_description_attributes','check_pallet_description_batch'):
        source=(PROJECT/'scripts'/f'{name}.py').read_text().replace('pallet-description-round3-','pallet-description-round6-');replacements={}
        for old,new in mapping.items():
            for pattern,value in ((f"p['class_id']=={old}",f"p['class_id']=={new}"),(f"locator('#classFilter').select_option('{old}')",f"locator('#classFilter').select_option('{new}')"),(f"g.classes['{old}']",f"g.classes['{new}']")):
                token=f'__ROUND6_CLASS_TOKEN_{len(replacements)}__';source=source.replace(pattern,token);replacements[token]=value
        for token,value in replacements.items():source=source.replace(token,value)
        if name=='check_pallet_description_simple':
            source=source.replace("page.locator('#observationText').input_value()=='' and page.locator('#descriptionText')", "page.locator('#observationText').input_value()==initial_description(g.proposals[q[0]])['observation'] and page.locator('#descriptionText')")
            source=source.replace('# First completion without any description interaction, including class reset and pan.',"# Only this temporary store exercises explicit blank observation.\n    page.locator('#observationText').fill('')")
        target=adapted/f'{name}.py'
        if target.exists():require(target.read_text()==source,'Preserve differing prior test adaptation')
        else:target.write_text(source)
    return mapping


def load_terms_suite(source):
    module=types.ModuleType('_round6_terms_GUI');module.__file__=str(PROJECT/'scripts/check_pallet_description_terms.py')
    exec(compile(source,module.__file__,'exec'),module.__dict__)
    # The terms extension's RELEASE constant intentionally still points to its
    # frozen round5 delivery. Rebind every runtime destination explicitly before
    # the inherited checker can archive/create ANY evidence directory.
    module.RELEASE=RELEASE;module.BASE=RELEASE;module.REVIEW_SETS=REVIEW_SETS;module.CODE=CODE
    module.bind_review_sets=bind_review_sets;module.binding_guard=binding_guard;module.sources_current=sources_current
    require(module.RELEASE==RELEASE and module.BASE==RELEASE and all('round6_' in str(s['root']) for s in module.REVIEW_SETS.values()),'Never run a new suite against an older release destination')
    return module


def check(mode):
    require(not (REVIEW_SETS[mode]['managed']/'public_access.json').exists(),'Do not replace browser acceptance for an active service')
    bind_review_sets();folder=RELEASE/mode;mapping=adapt_sources(mode)
    source=(PROJECT/'scripts/check_pallet_description_terms.py').read_text().replace('round5','round6')
    clear="require('清空1项' in page.locator('#structureTermsScope').inner_text(),'Clear not disclosed');"
    require(source.count(clear)==1,'Unexpected clear-preview test anchor')
    source=source.replace(clear,"texts=[(ed.store.get(k) or {}).get('description',initial_description(g.proposals[k]))['text'] for k in q]\n    expected_clears=sum(bool(t) and transform(t,['木质','已有项'],'delete')=='' for t in texts)\n    require(('清空'+str(expected_clears)+'项') in page.locator('#structureTermsScope').inner_text(),'Clear not disclosed');")
    frozen=folder/'adapted_test_code/check_pallet_description_terms.py'
    if frozen.exists():require(frozen.read_text()==source,'Preserve differing terms suite adaptation')
    else:frozen.write_text(source)
    module=load_terms_suite(source);module.check(mode)
    # The exact same source-guard policy is timed, without inventing a speedup
    # against a fabricated baseline. The established old implementation remains.
    path=PROJECT/'scripts/check_pallet_description_round4_fast.py';performance_source=path.read_text()
    marker="(('before',slow_guard),('after',fast_guard))";require(performance_source.count(marker)==1,'Unexpected performance factory loop')
    performance_source=performance_source.replace(marker,"(('current',fast_guard),)").replace("if name=='after':","if name=='current':")
    frozen=folder/'adapted_test_code/check_pallet_description_navigation.py'
    if frozen.exists():require(frozen.read_text()==performance_source,'Preserve differing navigation adaptation')
    else:frozen.write_text(performance_source)
    performance=types.ModuleType('_round6_navigation_benchmark');performance.__file__=str(path);exec(compile(performance_source,str(path),'exec'),performance.__dict__)
    performance.PRESENTATION=RELEASE;performance.REVIEW_SETS=REVIEW_SETS;performance.EVIDENCE=ROOT/'browser_performance';performance.fast_guard=binding_guard
    (performance.EVIDENCE/mode).mkdir(mode=0o700,parents=True);performance.benchmark(mode)
    ui=read(folder/'checks/terms_ui.json');base=read(SIMPLE_ROOT/'round5_terms_v1'/mode/'checks/ui_acceptance.json')
    termbase=read(SIMPLE_ROOT/'round5_terms_v1'/mode/'checks/terms_ui.json')
    base_names=set(base['implementation_sha256'])|set(termbase['implementation_sha256'])
    write(folder/'round6_browser_verification.json',dict(state='passed_round6_actual_task_desktop390_all_batch_and_fast_navigation',
        task_manifest_sha256=digest(REVIEW_SETS[mode]['root']/'manifest.json'),overlay_manifest_sha256=digest(folder/'manifest.json'),
        viewports=ui['viewports'],page_errors=ui['page_errors'],class_mapping=mapping,production_annotation_POSTs=0,
        implementation_sha256={n:digest(PROJECT/n) for n in CODE},base_implementation_sha256={n:digest(PROJECT/n) for n in base_names},
        adapted_test_sources={p.name:digest(p) for p in (folder/'adapted_test_code').iterdir()},terms_suite_adaptation_sha256=__import__('hashlib').sha256(source.encode()).hexdigest(),
        navigation_performance_sha256=digest(performance.EVIDENCE/mode/'navigation_benchmark.json'),
        performance_source_sha256=__import__('hashlib').sha256(performance_source.encode()).hexdigest()))


if __name__=='__main__':
    import argparse
    p=argparse.ArgumentParser();p.add_argument('mode',choices=REVIEW_SETS);args=p.parse_args();check(args.mode)
