"""Adapt proven real-browser safety flows to the new namespace and actual class mix."""
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.mask_model_training_data import read,jsonl,require,write
from pallet.cluster_targets import digest
from pallet.pallet_description_round4_data import sources_current
from pallet.pallet_description_round4_guard import binding_guard
from pallet.pallet_description_round4_release import RELEASE,REVIEW_SETS,bind_review_sets


def check(mode):
    bind_review_sets();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 actual10-item classes for complete isolated safety flows')
    selected={old:new for old,new in zip((1,2,3,4),available[:4])}
    folder=RELEASE/mode;adapted=folder/'adapted_test_code';adapted.mkdir(mode=0o700);modules={}
    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-round4-')
        # Replace each class token once against the original source (no cascading renumbering).
        replacements={}
        for old,new in selected.items():
            for pattern,replacement 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'__ROUND4_CLASS_TOKEN_{len(replacements)}__';source=source.replace(pattern,token);replacements[token]=replacement
        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.","# Actual model/human baseline was checked above; exercise an explicit blank observation in this temporary store.\n    page.locator('#observationText').fill('')")
        (adapted/f'{name}.py').write_text(source)
        module=types.ModuleType('_round4_'+name);module.__file__=str(PROJECT/'scripts'/f'{name}.py');exec(compile(source,module.__file__,'exec'),module.__dict__)
        modules[name]=module
    batch=modules['check_pallet_description_batch'];batch.binding_guard=binding_guard;batch.sources_current=sources_current
    batch.simple_flow=modules['check_pallet_description_simple'].flow
    batch.check(mode,release=RELEASE,single_flow=modules['check_pallet_description_single'].flow,attributes_flow=modules['check_pallet_description_attributes'].flow)
    write(folder/'round4_browser_verification.json',dict(state='passed_round4_actual_task_desktop_and390_safety',
        adapted_test_sources={p.name:digest(p) for p in adapted.iterdir()},class_mapping=selected,original_models_and_annotations_unchanged=True,
        implementation_sha256={n:digest(PROJECT/n) for n in ('pallet/pallet_description_round4_guard.py','scripts/serve_pallet_description_round4.py')},
        production_annotation_POSTs=0,wrapper_sha256=digest(__file__)))


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