"""Both batch modes, single-reviewer and joint navigation in actual temporary Chromium."""
import argparse
from copy import deepcopy
import json
from pathlib import Path
import sys

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 require
from pallet.pallet_description_attributes import RELEASE
from pallet.pallet_description_simple import initial_description
from check_pallet_description_simple import body
from check_mask_taxonomy_keyboard_ui import diag,draft,keypress
from check_mask_taxonomy_complete_ui import idle,failed
from check_mask_under50_ui import wait_value


def flow(page,context,base,g,server,width,out):
    ed=g.editor;q=[p['target_key'] for p in g.proposals.values() if p['class_id']==4];require(len(q)>8,'Need actual class4 queue')
    for key,action in ((q[0],'correct'),(q[1],'draft'),(q[2],'defer')):
        p=g.proposals[key];d={**initial_description(p),'text':'SYNTHETIC 各图原结构文字保留 '+key,'observation':'SYNTHETIC 各图原异常保留'}
        data=body(ed,p,d,action=action);data['note']='SYNTHETIC 原备注'
        if action=='draft':
            poly=deepcopy(p['polygon']);a,b=poly[:2];poly.insert(1,[(a[0]+b[0])/2,(a[1]+b[1])/2]);data['polygon']=poly;data['description_for']['polygon']=poly
        ed.save(key,data)
    outside={k:v for k,v in ed.store.summary().items() if k not in q}
    page.reload(wait_until='domcontentloaded');wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded')
    page.locator('#classFilter').select_option('4');page.locator('#cards .card').filter(has_text=q[3]).locator('button').click();idle(page,q[3])
    require(diag(page)['navigationIndex']==3 and diag(page)['navigationCount']==len(q),'Wrong filtered sequence')
    page.locator('#descriptionText').fill('SYNTHETIC 当前未保存结构文字不变');page.locator('#observationText').fill('SYNTHETIC 当前未保存异常不变');page.locator('#note').fill('SYNTHETIC 当前未保存备注不变')
    other_class=next(c for c in g.classes.values() if c['train_enabled'] and c['K']!=diag(page)['points']);page.locator('#editClass').select_option(str(other_class['class_id']))
    page.locator('#descriptionLegs').select_option('4');page.locator('#descriptionBeams').select_option('2');page.locator('#descriptionMaterial').select_option('金属')
    target=dict(legs=4,beams=2,material='金属');prefix=f'pallet-description-round3-{g.mode}-v1:'
    p=g.proposals[q[4]];poly=deepcopy(p['polygon']);poly[0][0]+=0.1
    local=dict(binding=ed.binding,baseRevision=0,polygon=poly,class_id=other_class['class_id'],reviewer='',note='SYNTHETIC 其他本机备注保留',restored=None,
        description={**initial_description(p),'text':'SYNTHETIC 其他本机文字保留','observation':'SYNTHETIC 其他本机异常保留'})
    raw=json.dumps(local,ensure_ascii=False,separators=(',',':'))
    page.evaluate('([prefix,key,raw])=>localStorage.setItem(prefix+location.host+":"+key,raw)',[prefix,q[4],raw])
    before={k:ed.store.get(k) for k in q};posts=server.batch_posts
    page.locator('#structureAttributesBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible')
    require(str(len(q)) in page.locator('#structureBatchScope').inner_text() and '不改结构描述文字' in page.locator('#structureBatchScope').inner_text() and all(v in page.locator('#structureBatchText').inner_text() for v in ('4','2','金属')),'Attributes preview omitted values or scope')
    page.locator('#structureBatchPreview').scroll_into_view_if_needed();page.screenshot(path=str(out/f'attributes_preview_{width}.png'))
    page.locator('#structureBatchCancel').click();require(server.batch_posts==posts and not ed.store.get(q[3]),'Cancel wrote attributes')
    # Changing one selected value after preview must not apply the old values.
    page.locator('#structureAttributesBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible');page.locator('#descriptionLegs').select_option('3');page.locator('#structureBatchApply').click()
    wait_value(page,'!taxonomyDiagnostics().saving&&document.getElementById("saveStatus").textContent.includes("预览后本机草稿已变化")')
    require(server.batch_posts==posts,'Changed selection submitted stale preview');page.locator('#structureBatchCancel').click();page.locator('#descriptionLegs').select_option('4')
    # Switching buttons switches the explicit preview mode, never mixes text/attributes.
    page.locator('#structureAttributesBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible');page.locator('#structureBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible')
    require('仅同步结构描述文本' in page.locator('#structureBatchScope').inner_text(),'Batch preview modes mixed');page.locator('#structureBatchCancel').click()
    page.locator('#structureAttributesBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible')
    p=g.proposals[q[5]];ed.save(q[5],body(ed,p,{**initial_description(p),'text':'SYNTHETIC 其他窗口新文字','observation':'SYNTHETIC 其他窗口新异常'},action='draft'))
    page.locator('#structureBatchApply').click();wait_value(page,'!taxonomyDiagnostics().saving&&document.getElementById("saveStatus").textContent.includes("版本冲突")')
    require(ed.store.get(q[0])==before[q[0]] and not ed.store.get(q[3]) and len(ed.store.history(q[5]))==1,'Conflict partially applied attributes')
    page.reload(wait_until='domcontentloaded');wait_value(page,'window.taxonomyDiagnostics&&taxonomyDiagnostics().loaded');page.locator('#classFilter').select_option('4');page.locator('#cards .card').filter(has_text=q[3]).locator('button').click();idle(page,q[3])
    before={k:ed.store.get(k) for k in q};current_local=draft(page);server.batch_gate.clear();server.hold_batch=True;server.fail_batch_reply=True
    page.locator('#structureAttributesBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible');page.locator('#structureBatchApply').click();wait_value(page,'taxonomyDiagnostics().saving')
    require(page.locator('#structureAttributesBatch').is_disabled() and page.locator('#structureBatch').is_disabled() and page.locator('#descriptionMaterial').is_disabled(),'Attribute batch busy lock missing')
    single_posts=server.posts
    for k in ('a','d','Control+s'):keypress(page,k,'canvas')
    require(server.posts==single_posts,'Busy attributes triggered joint save');server.batch_gate.set();server.hold_batch=False
    wait_value(page,'!taxonomyDiagnostics().saving&&document.getElementById("saveStatus").textContent.includes("SYNTHETIC reply lost")')
    require(ed.store.get(q[3])['revision']==1 and diag(page)['expectedRevision']==0,'Lost response did not preserve baseline')
    counts={k:len(ed.store.history(k)) for k in q};page.locator('#structureBatchApply').click()
    wait_value(page,'!taxonomyDiagnostics().saving&&document.getElementById("saveStatus").textContent.includes("已批量确认")')
    require('未重复写入' in page.locator('#saveStatus').inner_text(),'Attributes retry did not replay')
    for key in q:
        new=ed.store.get(key);old=before[key];d=old['description'] if old else initial_description(g.proposals[key])
        require(new['description']=={**d,**target} and new['reviewer']=='复核人1' and len(ed.store.history(key))==counts[key],'Wrong fields changed or retry duplicated events')
        require(new['class_id']==(old['class_id'] if old else g.proposals[key]['class_id']) and new['polygon']==(old['polygon'] if old else g.proposals[key]['polygon']) and new['action']==(old['action'] if old else 'draft'),'Attribute batch changed geometry/class/completion')
        if old:require(ed.store.history(key)[1]==old,'Attribute batch rewrote history')
    require(all(ed.store.get(k)==v for k,v in outside.items()),'Attributes modified outside filter')
    current=draft(page);require(current['baseRevision']==1 and current['description']=={**current_local['description'],**target} and current['class_id']==current_local['class_id'] and current['polygon']==current_local['polygon'] and current['note']==current_local['note'],'Current draft text/anomaly/geometry lost')
    other=page.evaluate('([prefix,key])=>JSON.parse(localStorage.getItem(prefix+location.host+":"+key))',[prefix,q[4]])
    require(other=={**local,'baseRevision':1,'description':{**local['description'],**target}},'Other draft incorrectly rebased or overwritten')
    require(page.evaluate('([prefix,key,raw])=>Object.keys(localStorage).some(k=>k.startsWith(prefix+location.host+":structure-batch-backup:")&&JSON.parse(localStorage.getItem(k)).drafts[key]===raw)',[prefix,q[4],raw]),'Original draft backup missing')
    page.locator('#nextTarget').click();failed(page,'必须为K',q[3]);require(len(ed.store.history(q[3]))==1,'Attribute batch bypasses K')
    # Unknown selections propagate as unknown, not replaced by class templates.
    page.locator('#descriptionLegs').select_option('');page.locator('#descriptionBeams').select_option('');page.locator('#descriptionMaterial').select_option('无法判断')
    page.locator('#structureAttributesBatch').click();page.locator('#structureBatchPreview').wait_for(state='visible')
    require(page.locator('#structureBatchText').inner_text().count('无法判断')==3 and '原样应用' in page.locator('#structureBatchScope').inner_text(),'Unknown values not disclosed')
    page.locator('#structureBatchApply').click();wait_value(page,'!taxonomyDiagnostics().saving&&document.getElementById("saveStatus").textContent.includes("已批量确认")')
    for key in q:
        new=ed.store.get(key);old=before[key];d=old['description'] if old else initial_description(g.proposals[key])
        require(new['description']=={**d,'legs':None,'beams':None,'material':'无法判断'} and new['revision']==(old['revision'] if old else 0)+2,'Unknown fields filled from template or unrelated description changed')
    page.locator('#structureAttributesBatch').scroll_into_view_if_needed();page.screenshot(path=str(out/f'attributes_saved_{width}.png'));page.locator('#close').click()
    require(page.evaluate('document.documentElement.scrollWidth<=innerWidth'),'Attributes narrow UI overflow')
    return dict(only_three_fields=True,idempotent_retry=True,unknown_values=True,drafts_preserved=True,scope_count=len(q),cancel_no_write=True,
        all_or_nothing409=True,history_append_only=True,independent_preview_modes=True,preview_value_change_blocked=True,busy_lock=True,strictK_preserved=True)


if __name__=='__main__':
    from check_pallet_description_batch import check
    from check_pallet_description_single import flow as single_flow
    p=argparse.ArgumentParser();p.add_argument('mode',choices=('new','existing'));a=p.parse_args();check(a.mode,release=RELEASE,single_flow=single_flow,attributes_flow=flow)
