"""Proven atomic/batch/409 flows on actual new tasks and isolated temporary DBs."""
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,write,jsonl,require
from pallet.cluster_targets import digest
from pallet.pallet_description_round5_data import binding_guard,sources_current,ROOT
from pallet.pallet_description_round5_release import REVIEW_SETS,RELEASE,bind_review_sets

CODE=('pallet/pallet_description_round5_data.py','pallet/pallet_description_round5_release.py','pallet/pallet_description_parallel_guard.py',
    'scripts/check_pallet_description_round5_ui.py','scripts/serve_pallet_description_round5.py')


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 isolated safety flows')
    mapping=dict(zip((1,2,3,4),available[:4]));folder=RELEASE/mode;adapted=folder/'adapted_test_code';require(not adapted.exists(),'Preserve prior UI attempt');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-round5-');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'__ROUND5_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.',"# Baseline checked above; only this temporary store exercises an explicit blank observation.\n    page.locator('#observationText').fill('')")
        (adapted/f'{name}.py').write_text(source);module=types.ModuleType('_round5_'+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)
    # Explicit D/A timings use the exact same fast content guard as deployment.
    import check_pallet_description_round4_fast as performance
    performance.PRESENTATION=RELEASE;performance.REVIEW_SETS=REVIEW_SETS;performance.EVIDENCE=ROOT/'browser_performance';performance.fast_guard=binding_guard
    performance.slow_guard=binding_guard
    (performance.EVIDENCE/mode).mkdir(mode=0o700,parents=True);performance.benchmark(mode)
    write(folder/'round5_browser_verification.json',dict(state='passed_round5_actual_task_desktop_and390_atomic_batch_and_fast_navigation',
        adapted_test_sources={p.name:digest(p) for p in adapted.iterdir()},class_mapping=mapping,production_annotation_POSTs=0,
        implementation_sha256={n:digest(PROJECT/n) for n in CODE},task_manifest_sha256=digest(REVIEW_SETS[mode]['root']/'manifest.json'),
        performance_sha256=digest(performance.EVIDENCE/mode/'navigation_benchmark.json')))


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