from pathlib import Path

THEME=Path('/opt/cosmosluminosity/content/themes/clean')

DATA={
'ru':{
'file':'page-next-chapter-experiment.hbs',
'hero_old':'Один вопрос · одна рабочая гипотеза · один обратимый шаг · личная Experiment Card',
'hero_new':'Карта перехода · два реалистичных продолжения · один эксперимент · личный Transition Brief',
'time_old':'10–15 минут','time_new':'20–25 минут',
'about_old':'Ты назовёшь то, что стало тесным, сохранишь важное, услышишь разные источники собственной информации и создашь действие, которое способно дать реальные данные. Это не тест личности, не предсказание и не совет увольняться.',
'about_new':'Ты разберёшь не только то, что стало тесным, но и функции, которые выполняет нынешняя работа, цену каждого возможного продолжения и предположение, которое стоит проверить до большого решения. В финале появится не результат теста, а твой личный Transition Brief.',
'step2_anchor':'<p class="form-error" data-error></p></fieldset>',
'step2_extra':'<div class="depth-divider"><span>Глубже</span></div><label class="field"><span>Что эта работа даёт тебе помимо дохода?</span><textarea name="hidden_functions" rows="4" placeholder="Идентичность, статус, принадлежность, структура дня, интеллектуальная интенсивность, безопасность, видимость…"></textarea></label><label class="field"><span>Что ты готова отпустить, даже если оно когда-то было ценно?</span><textarea name="release" rows="3" placeholder="Роль, ожидание, способ доказывать ценность, прежний темп…"></textarea></label><label class="field"><span>Что стоит не бросать, а пересобрать?</span><textarea name="redesign" rows="3" placeholder="Ответственность, расписание, модель дохода, способ быть видимой…"></textarea></label>',
'step3_extra':'<div class="depth-divider"><span>Сопоставление</span></div><label class="field"><span>В чём источники информации противоречат друг другу?</span><textarea name="tension" rows="3" placeholder="Например: разум видит риск, а состояние оживает; желание зовёт, но реальность пока не поддерживает масштаб шага"></textarea></label><label class="field"><span>Какие факты и обязательства нельзя исключить из решения?</span><textarea name="reality" rows="3" placeholder="Деньги, время, здоровье, отношения, договорённости, география, сроки"></textarea></label>',
'step4_extra':'<div class="depth-divider"><span>Возможные продолжения</span></div><label class="field"><span>Продолжение A — минимальная пересборка</span><textarea name="future_a" rows="3" placeholder="Что можно изменить, сохранив большую часть нынешней профессиональной жизни?"></textarea></label><label class="field"><span>Продолжение B — более смелое движение</span><textarea name="future_b" rows="3" placeholder="Какое направление становится возможным, если дать ему реальное место?"></textarea></label><label class="field"><span>Какое ключевое предположение эксперимент должен проверить?</span><textarea name="assumption" rows="3" placeholder="Например: в другом ритме моё мастерство останется ценным и я не потеряю влияние"></textarea></label><div class="protocol-grid"><label class="field"><span>Окно эксперимента</span><textarea name="duration" rows="2" placeholder="Один разговор, один рабочий блок, 72 часа, одна неделя…"></textarea></label><label class="field"><span>Разговор, который требуется провести</span><textarea name="conversation" rows="2" placeholder="С кем и о чём?"></textarea></label><label class="field"><span>Сигнал продолжать</span><textarea name="continue_rule" rows="2" placeholder="Что покажет, что направление заслуживает следующего шага?"></textarea></label><label class="field"><span>Сигнал остановиться или пересобрать</span><textarea name="stop_rule" rows="2" placeholder="Что будет достаточным основанием не продолжать в прежнем виде?"></textarea></label></div><label class="field"><span>Главный вопрос Evidence Review</span><textarea name="review_question" rows="3" placeholder="Что должно стать яснее после контакта гипотезы с реальностью?"></textarea></label>',
'result_label':'Твой личный документ','result_title':'Transition Decision & Experiment Brief','result_intro':'Не описание твоего типа и не готовый ответ. Это рабочая архитектура следующего выбора: что сохранить, что перестало работать, какие продолжения реалистичны и какие данные создать до большого решения.',
'labels':{'hidden_functions':'Что удерживает нынешняя работа','release':'Что я отпускаю','redesign':'Что я пересобираю','tension':'Главное внутреннее противоречие','reality':'Практическая реальность','future_a':'Продолжение A · Пересборка','future_b':'Продолжение B · Новое движение','assumption':'Ключевое предположение','duration':'Окно эксперимента','conversation':'Разговор, который требуется провести','continue_rule':'Сигнал продолжать','stop_rule':'Сигнал остановиться или пересобрать','review_question':'Вопрос для Evidence Review'},
'print':'Скачать / распечатать Brief','copy':'Скопировать содержание',
},
'en':{
'file':'page-next-chapter-experiment-en.hbs',
'hero_old':'One question · one working hypothesis · one reversible step · your Experiment Card',
'hero_new':'A transition map · two credible continuations · one experiment · your personal Transition Brief',
'time_old':'10–15 minutes','time_new':'20–25 minutes',
'about_old':'Name what has become too small, preserve what matters, listen to different sources of your own information, and create an action capable of producing real evidence. This is not a personality test, prediction, or advice to resign.',
'about_new':'Examine not only what has become too small, but the functions your current work performs, the cost of each possible continuation, and the assumption worth testing before a major decision. You leave with a personal Transition Brief—not a personality-test result.',
'step2_anchor':'<p class="form-error" data-error></p></fieldset>',
'step2_extra':'<div class="depth-divider"><span>Go deeper</span></div><label class="field"><span>What does this work give you beyond income?</span><textarea name="hidden_functions" rows="4" placeholder="Identity, status, belonging, structure, intellectual intensity, security, visibility…"></textarea></label><label class="field"><span>What are you willing to release, even if it once mattered?</span><textarea name="release" rows="3" placeholder="A role, expectation, way of proving value, former pace…"></textarea></label><label class="field"><span>What should be redesigned rather than abandoned?</span><textarea name="redesign" rows="3" placeholder="Responsibility, schedule, income model, way of being visible…"></textarea></label>',
'step3_extra':'<div class="depth-divider"><span>Reconcile the signals</span></div><label class="field"><span>Where do your sources of information contradict one another?</span><textarea name="tension" rows="3" placeholder="For example: the mind sees risk while the state comes alive; desire calls, while reality does not yet support the scale"></textarea></label><label class="field"><span>Which facts and responsibilities must remain inside the decision?</span><textarea name="reality" rows="3" placeholder="Money, time, health, relationships, agreements, geography, timing"></textarea></label>',
'step4_extra':'<div class="depth-divider"><span>Credible continuations</span></div><label class="field"><span>Continuation A — minimum viable redesign</span><textarea name="future_a" rows="3" placeholder="What could change while preserving most of your current professional life?"></textarea></label><label class="field"><span>Continuation B — a bolder movement</span><textarea name="future_b" rows="3" placeholder="What direction becomes possible if you give it a real place to begin?"></textarea></label><label class="field"><span>What key assumption must the experiment test?</span><textarea name="assumption" rows="3" placeholder="For example: at a different pace, my mastery will remain valuable and I will not lose influence"></textarea></label><div class="protocol-grid"><label class="field"><span>Experiment window</span><textarea name="duration" rows="2" placeholder="One conversation, one work block, 72 hours, one week…"></textarea></label><label class="field"><span>Conversation that needs to happen</span><textarea name="conversation" rows="2" placeholder="With whom, and about what?"></textarea></label><label class="field"><span>Signal to continue</span><textarea name="continue_rule" rows="2" placeholder="What would show this direction deserves a next step?"></textarea></label><label class="field"><span>Signal to stop or redesign</span><textarea name="stop_rule" rows="2" placeholder="What would be sufficient reason not to continue in its current form?"></textarea></label></div><label class="field"><span>Primary Evidence Review question</span><textarea name="review_question" rows="3" placeholder="What should become clearer after the hypothesis meets real life?"></textarea></label>',
'result_label':'Your personal document','result_title':'Transition Decision & Experiment Brief','result_intro':'Not a personality description and not a ready-made answer. This is a working architecture for your next choice: what to preserve, what no longer works, which continuations are credible, and what evidence to create before a major decision.',
'labels':{'hidden_functions':'What my current work is holding','release':'What I release','redesign':'What I redesign','tension':'The central tension','reality':'Practical reality','future_a':'Continuation A · Redesign','future_b':'Continuation B · New movement','assumption':'Key assumption','duration':'Experiment window','conversation':'Conversation that needs to happen','continue_rule':'Signal to continue','stop_rule':'Signal to stop or redesign','review_question':'Evidence Review question'},
'print':'Download / print the Brief','copy':'Copy the content',
}}

def upgrade(lang,c):
 p=THEME/c['file']; s=p.read_text()
 # Idempotency guard: start from current v1 only.
 if 'data-brief-version="2"' in s:
  return
 s=s.replace('<div class="experiment-page" data-experiment', '<div class="experiment-page" data-experiment data-brief-version="2"',1)
 s=s.replace(c['hero_old'],c['hero_new'],1).replace(c['time_old'],c['time_new'],1).replace(c['about_old'],c['about_new'],1)
 # Step-specific insertion by fieldset markers.
 pos=s.index('<fieldset class="exp-step" data-step="2"')
 end=s.index(c['step2_anchor'],pos)
 s=s[:end]+c['step2_extra']+s[end:]
 pos=s.index('<fieldset class="exp-step" data-step="3"')
 end=s.index('<p class="form-error" data-error></p></fieldset>',pos)
 s=s[:end]+c['step3_extra']+s[end:]
 pos=s.index('<fieldset class="exp-step" data-step="4"')
 end=s.index('<p class="form-error" data-error></p></fieldset>',pos)
 s=s[:end]+c['step4_extra']+s[end:]
 # Upgrade result header.
 start=s.index('<section class="exp-result"')
 grid=s.index('<div class="card-grid">',start)+len('<div class="card-grid">')
 head=s[start:grid]
 import re
 head=re.sub(r'<p class="experiment-label">.*?</p><h2>.*?</h2><p>.*?</p>',f'<p class="experiment-label">{c["result_label"]}</p><h2>{c["result_title"]}</h2><p>{c["result_intro"]}</p>',head,1)
 head=head.replace('<article class="experiment-card" data-card>','<article class="experiment-card brief-sheet" data-card><header class="brief-cover"><span>COSMOS LUMINOSITY</span><b>THE THOUGHTFUL TRANSITION</b><em>Decision architecture · Real-world evidence</em></header>')
 head=head.replace('<div class="card-mark">COSMOS LUMINOSITY · THE THOUGHTFUL TRANSITION</div>','')
 s=s[:start]+head+s[grid:]
 # Add deeper result fields before review.
 review=s.index('<section class="card-item card-review">',start)
 extra=''.join(f'<section class="card-item card-{k}"><h3>{v}</h3><div data-out="{k}"></div></section>' for k,v in c['labels'].items())
 s=s[:review]+extra+s[review:]
 s=s.replace('Сохранить / распечатать',c['print'],1).replace('Скопировать карточку',c['copy'],1)
 s=s.replace('Save / print',c['print'],1).replace('Copy the card',c['copy'],1)
 # Replace runtime IIFE with a secure deeper version, preserving copy object.
 script_start=s.index('(()=>{const root=',s.index('<script>'))
 script_end=s.index('})();',script_start)+5
 js=r'''(()=>{const root=document.querySelector('[data-experiment]');if(!root)return;const c=window.EXPERIMENT_COPY,workspace=root.querySelector('[data-workspace]'),form=root.querySelector('[data-form]'),steps=[...root.querySelectorAll('[data-step]')],result=root.querySelector('[data-result]'),next=root.querySelector('[data-next]'),back=root.querySelector('[data-back]');let current=1;const val=n=>form.elements[n]?.value.trim()||'',checked=n=>[...form.querySelectorAll(`[name="${n}"]:checked`)].map(x=>x.value),radio=n=>form.querySelector(`[name="${n}"]:checked`)?.value||'',write=(k,v)=>{const e=root.querySelector(`[data-out="${k}"]`);if(e)e.textContent=v||c.empty};function show(n){current=n;steps.forEach(s=>s.hidden=+s.dataset.step!==n);back.hidden=n===1;next.textContent=n===4?c.create:c.next;root.querySelectorAll('[data-progress]').forEach(x=>x.classList.toggle('active',+x.dataset.progress<=n));root.querySelector('[data-progress-bar]').style.width=((n-1)/3*100)+'%';workspace.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'})}function error(msg){steps[current-1].querySelector('[data-error]').textContent=msg;return false}function validate(){steps[current-1].querySelector('[data-error]').textContent='';if(current===1&&(!val('question')||!radio('stage')))return error(c.required);if(current===2&&(!radio('tight')||checked('preserve').length===0||!val('hidden_functions')||!val('release')||!val('redesign')))return error(c.required);if(current===3&&(!val('mind')||!val('body')||!val('state')||!val('desire')||!val('tension')||!val('reality')))return error(c.required);if(current===4&&(!val('hypothesis')||(!radio('experiment')&&!val('experiment_custom'))||checked('evidence').length===0||!val('future_a')||!val('future_b')||!val('assumption')||!val('duration')||!val('continue_rule')||!val('stop_rule')||!val('review_question')))return error(c.required);return true}function populateExperiment(){const tight=radio('tight');form.elements.hypothesis.value=c.hypotheses[tight]||'';const wrap=root.querySelector('[data-experiment-options]');wrap.replaceChildren(...(c.experiments[tight]||[]).map((t,i)=>{const l=document.createElement('label'),x=document.createElement('input'),z=document.createElement('span');l.className='choice';x.type='radio';x.name='experiment';x.value=i;z.textContent=t;l.append(x,z);return l}))}function mapped(keys,map){return keys.map(k=>map[k]||k).join(' · ')||c.empty}function make(){workspace.hidden=false;const tight=radio('tight'),exp=val('experiment_custom')||((c.experiments[tight]||[])[+radio('experiment')]||c.empty);write('question',val('question'));write('tight',c.tight_names[tight]);write('preserve',mapped(checked('preserve'),c.preserve_names)+(val('preserve_other')?' · '+val('preserve_other'):''));write('unknown',val('unknown'));write('hypothesis',val('hypothesis'));write('experiment',exp);write('boundary',val('boundary'));write('evidence',mapped(checked('evidence'),c.evidence_names));['hidden_functions','release','redesign','tension','reality','future_a','future_b','assumption','duration','conversation','continue_rule','stop_rule','review_question'].forEach(k=>write(k,val(k)));const sig=root.querySelector('[data-out="signals"]');sig.replaceChildren();['mind','body','state','desire'].forEach((k,i)=>{if(i)sig.append(document.createElement('br'));const b=document.createElement('b');b.textContent=c.signal_names[k]+': ';sig.append(b,document.createTextNode(val(k)))});form.hidden=true;root.querySelector('.progress-wrap').hidden=true;result.hidden=false;result.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'})}root.querySelector('[data-start]').addEventListener('click',()=>{workspace.hidden=false;show(1)});next.addEventListener('click',()=>{if(!validate())return;if(current===3){populateExperiment();show(4)}else if(current===4)make();else show(current+1)});back.addEventListener('click',()=>show(current-1));root.querySelector('[data-print]').addEventListener('click',()=>window.print());root.querySelector('[data-copy]').addEventListener('click',async()=>{const text=root.querySelector('[data-card]').innerText;try{await navigator.clipboard.writeText(text);root.querySelector('[data-copy-status]').textContent=c.copied}catch(e){root.querySelector('[data-copy-status]').textContent=text}});root.querySelector('[data-restart]').addEventListener('click',()=>{form.reset();form.hidden=false;result.hidden=true;root.querySelector('.progress-wrap').hidden=false;show(1)});})();'''
 s=s[:script_start]+js+s[script_end:]
 p.write_text(s)

for lang,c in DATA.items(): upgrade(lang,c)

css=THEME/'assets/css/experiment.css'
s=css.read_text()
marker='/* TRANSITION BRIEF V2 */'
if marker not in s:
 s+='''\n/* TRANSITION BRIEF V2 */
.depth-divider{display:flex;align-items:center;gap:16px;margin:50px 0 24px;color:#633589;font:600 11px var(--sans);letter-spacing:.16em;text-transform:uppercase}.depth-divider:after{content:"";height:1px;flex:1;background:rgba(55,30,71,.22)}.protocol-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 24px}.exp-result{scroll-margin-top:110px}.brief-sheet{position:relative;overflow:hidden;background:#0c0712;border:1px solid rgba(218,188,112,.55);box-shadow:22px 22px 0 #d7c4ec}.brief-sheet:before{content:"";position:absolute;width:380px;height:380px;right:-180px;top:-180px;border:1px solid rgba(240,216,69,.23);transform:rotate(35deg);box-shadow:0 0 0 42px rgba(105,44,162,.08),0 0 0 86px rgba(105,44,162,.05)}.brief-cover{position:relative;z-index:1;display:grid;grid-template-columns:1fr auto;gap:8px 20px;padding-bottom:34px;border-bottom:1px solid rgba(218,188,112,.35);margin-bottom:1px}.brief-cover span{font:600 13px var(--sans);letter-spacing:.18em;color:#f2d548}.brief-cover b{font:500 12px var(--sans);letter-spacing:.13em;color:#d8b970}.brief-cover em{grid-column:1/-1;font:italic 28px/1.1 var(--serif);color:#f7f1e8}.brief-sheet .card-grid{grid-template-columns:repeat(12,1fr);background:rgba(225,207,255,.13)}.brief-sheet .card-item{grid-column:span 6;min-height:145px}.brief-sheet .card-question,.brief-sheet .card-signals,.brief-sheet .card-hypothesis,.brief-sheet .card-experiment,.brief-sheet .card-hidden_functions,.brief-sheet .card-tension,.brief-sheet .card-reality,.brief-sheet .card-assumption,.brief-sheet .card-review_question{grid-column:1/-1}.brief-sheet .card-future_a,.brief-sheet .card-future_b{min-height:190px;background:#160d20}.brief-sheet .card-experiment{background:linear-gradient(120deg,#27123d,#160d20);border-left:3px solid #f2d548}.brief-sheet .card-item h3{font-size:10px}.brief-sheet .card-item div{font-size:19px}.brief-sheet .card-review{grid-column:span 6}.brief-sheet footer{border-top:1px solid rgba(218,188,112,.3);padding-top:24px}@media(max-width:760px){.protocol-grid{grid-template-columns:1fr}.brief-cover{grid-template-columns:1fr}.brief-cover em{font-size:23px}.brief-sheet .card-grid{grid-template-columns:1fr}.brief-sheet .card-item,.brief-sheet .card-question,.brief-sheet .card-signals,.brief-sheet .card-hypothesis,.brief-sheet .card-experiment,.brief-sheet .card-hidden_functions,.brief-sheet .card-tension,.brief-sheet .card-reality,.brief-sheet .card-assumption,.brief-sheet .card-review_question,.brief-sheet .card-review{grid-column:1}}
@media print{@page{size:A4;margin:10mm}.brief-sheet{box-shadow:none;border:1px solid #5d4770;padding:9mm;background:#0c0712!important}.brief-sheet:before{display:none}.brief-sheet .card-item{min-height:0;padding:4mm;break-inside:avoid}.brief-sheet .card-item div{font-size:11pt;line-height:1.3}.brief-cover{padding-bottom:5mm}.brief-cover em{font-size:20pt}.experiment-card footer{margin-top:5mm}.site-shell{display:block}.exp-result{max-width:none}}
'''
 css.write_text(s)
print('Transition Brief v2 applied')
