from pathlib import Path
import json,shutil,re,hashlib
W=Path('/mnt/data/work4110');R=W/'site';D=W/'inputs/документы-и-доказательства-4.10.0-wip';M=W/'inputs/память-уаикс-4.10.0-wip';E=R/'доказательства/редакция-4.11.0';A=E/'исходники'
def save(p):
 q=A/(p.relative_to(R).as_posix()+'.txt');q.parent.mkdir(parents=True,exist_ok=True)
 if not q.exists():shutil.copyfile(p,q)
def dump(p,x):p.write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n')
# Restore old evidence byte for byte: current trials must never overwrite history.
shutil.copytree(D/'доказательства/редакция-4.10.0',R/'доказательства/редакция-4.10.0',dirs_exist_ok=True)
shutil.copy2(W/'run/настоящий-браузер-первичная-проба.json',E/'настоящий-браузер.json')
# Archive the previous standalone memory as an exact immutable input ZIP.
shutil.copy2(Path('/mnt/data/память-уаикс-4.10.0-wip.zip'),R/'загрузки/память-уаикс-4.10.0-wip.zip')
profile=json.loads((R/'данные/профиль-схем-4.10.0.json').read_text());new=json.loads(json.dumps(profile));new['редакция']='4.11.0-wip'
for k,v in profile['файлы'].items():
 if '4.10.0' in v:
  src=R/v.lstrip('/');dst=R/v.lstrip('/').replace('4.10.0','4.11.0');dst.write_text(src.read_text().replace('4.10.0','4.11.0'));new['файлы'][k]=v.replace('4.10.0','4.11.0');new['файлы'][k+'4100']=v
for name in ['схема-оценки-когнитивной-свободы','схемы-лаборатории']:
 p=R/'данные'/f'{name}-4.10.0.json';(R/'данные'/f'{name}-4.11.0.json').write_text(p.read_text().replace('4.10.0','4.11.0'))
dump(R/'данные/профиль-схем-4.11.0.json',new)
for p in (R/'ресурсы/сценарии').glob('*.js'):
 save(p);p.write_text(p.read_text().replace('4.10.0','4.11.0').replace('4.10-1','4.11-1'))
p=R/'ресурсы/сценарии/доказательный-контур.js';s=p.read_text()
s=s.replace("'4.9.0-wip'].includes", "'4.9.0-wip','4.10.0-wip'].includes")
s=s.replace("a.редакция_схемы === '4.9.0-wip' ? schemas.audit490 : schemas.audit", "a.редакция_схемы === '4.9.0-wip' ? schemas.audit490 : a.редакция_схемы === '4.10.0-wip' ? schemas.audit4100 : schemas.audit")
s=s.replace("version==='4.9.0-wip'?'490':null", "version==='4.9.0-wip'?'490':version==='4.10.0-wip'?'4100':null")
s=s.replace("version==='4.9.0-wip'?schemas.registry490:version===RELEASE", "version==='4.9.0-wip'?schemas.registry490:version==='4.10.0-wip'?schemas.registry4100:version===RELEASE")
s=s.replace("candidate?.запись?.редакция_схемы==='4.9.0-wip'?schemas.callReceipt490:schemas.callReceipt", "candidate?.запись?.редакция_схемы==='4.9.0-wip'?schemas.callReceipt490:candidate?.запись?.редакция_схемы==='4.10.0-wip'?schemas.callReceipt4100:schemas.callReceipt")
s=s.replace("'война/односторонний-перенос/4.11.0-1'].includes", "'война/односторонний-перенос/4.10.0-1','война/односторонний-перенос/4.11.0-1'].includes")
s=s.replace('или 4.9.0 нужного вида.', '4.9.0 или 4.10.0 нужного вида.')
s=s.replace("'война-аудит-когнитивной-свободы-4-9'].includes", "'война-аудит-когнитивной-свободы-4-9','война-аудит-когнитивной-свободы-4-10'].includes")
s=s.replace("'война-реестр-требований-4-9'].includes", "'война-реестр-требований-4-9','война-реестр-требований-4-10'].includes")
s=s.replace("key.replace(/4-[56789]$/,'4-10')", "key.replace(/4-(?:[56789]|10)$/,'4-11')")
p.write_text(s)
p=R/'ресурсы/сценарии/методика.js';p.write_text(p.read_text().replace("когнитивной-свободы-4-10'", "когнитивной-свободы-4-11'").replace("требований-4-10'", "требований-4-11'"))
# Current HTML derivatives only, keep the 18 research main bodies exact.
pages=[]
for p in sorted(R.rglob('*.html')):
 rel=p.relative_to(R).as_posix()
 if rel.startswith(('доказательства/','docs/архив-выпусков/')):continue
 save(p);old=p.read_text();s=old.replace('4.10.0','4.11.0');s=s.replace('рубежей-4-10.uai','рубежей-4-11.uai').replace('выпуске-4-10.uai','выпуске-4-11.uai')
 if 'docs/исследования/' in rel:
  main=re.search(r'<main\b[^>]*>.*?</main>',old,re.S)
  if main:s=re.sub(r'<main\b[^>]*>.*?</main>',lambda _:main.group(),s,count=1,flags=re.S)
 if 'id="редакция-черновика"' in s and 'value="4-10"' not in s:s=s.replace('<option value="4-9">4.9.0</option>','<option value="4-9">4.9.0</option><option value="4-10">4.10.0</option>')
 p.write_text(s);pages.append({'путь':rel,'до':hashlib.sha256(old.encode()).hexdigest(),'после':hashlib.sha256(s.encode()).hexdigest()})
dump(E/'редакционные-производные-подготовка.json',pages)
for n in ['service-worker.js','служба.js','ВЕРСИЯ.txt','sitemap.xml','.htaccess','robots.txt']:
 p=R/n
 if p.exists():save(p);p.write_text(p.read_text().replace('4.8.0','4.11.0').replace('4.9.0','4.11.0').replace('4.10.0','4.11.0'))
# Clone current replay tools, never modify old scripts; shared helpers use runtime roots.
for p in list((R/'инструменты').iterdir()):
 if not p.is_file() or '4-10' not in p.name or p.name.startswith('собрать-пакеты'):continue
 q=p.with_name(p.name.replace('4-10','4-11'));s=p.read_text().replace('4.10.0','4.11.0').replace('4-10','4-11').replace('4100','4110');q.write_text(s)
# Resource command has a deliberately chosen name, not the inherited misleading command.
p=R/'инструменты/измерить-ресурсы-4-11.cjs';s=(R/'инструменты/измерить-ресурсы-4-7-повтор-4-11.cjs').read_text().replace('измерить-ресурсы-4-7-повтор-4-11.cjs','измерить-ресурсы-4-11.cjs');p.write_text(s)
print('version prepared; public pages',len(pages),'profile files',len(new['файлы']))
