from pathlib import Path
from html import escape
import json

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

D={
'ru':{
 'layout':'default','file':'page-next-chapter-experiment.hbs','lang':'ru','url':'https://www.cosmosluminosity.com/next-chapter-experiment/','other':'https://www.cosmosluminosity.com/next-chapter-experiment-en/',
 'title':'Что ты можешь не замечать в своём профессиональном переходе?','page':'Различить профессиональный переход — Cosmos Luminosity','desc':'Короткое исследование: один неочевидный паттерн, основания и эксперимент до большого профессионального решения.','eyebrow':'Бесплатное исследование · 4–6 минут','lead':'Ответь на несколько точных вопросов. Ты получишь не пересказ ответов, а возможное прочтение того, что связывает их между собой.','meta':'Без регистрации · почти без письма · ответы остаются в браузере','start':'Увидеть возможный паттерн','note':'Это не тест личности, диагноз или решение за тебя. Интерпретация остаётся гипотезой, которую можно проверить в реальности.','back':'Назад','next':'Дальше','result_btn':'Показать моё прочтение','required':'Выбери ответ, чтобы продолжить.','limit':'Выбери не больше двух вариантов.','steps':['Вопрос','Напряжение','Контраст','Живое','Удерживает','Расхождение'],
 'q1':'Какой вопрос сейчас ближе всего к твоему?','q1o':[['leave','Я думаю об уходе из профессии'],['role','Я хочу изменить роль, но не понимаю, какую'],['way','Я больше не согласна работать прежним способом'],['notmine','Внешне всё хорошо, но внутри это больше не моё'],['next','Я чувствую следующую главу, но не вижу её очертаний']],
 'q2':'В какие моменты сопротивление становится особенно сильным?','q2h':'Выбери максимум два','q2o':[['rescue','Когда требуется снова спасать ситуацию'],['available','Когда требуется постоянно быть доступной'],['stagnant','Когда я выполняю знакомую работу без развития'],['noagency','Когда решения принимаются без моего влияния'],['oldself','Когда требуется изображать прежнюю версию себя'],['meaningless','Когда результат больше не кажется значимым'],['even_good','Даже когда условия хорошие и давление невелико']],
 'q3':'Представь: доход сохранён, команда подходит, ритм спокойнее, границы уважаются. Что происходит внутри?','q3o':[['returns','Я чувствую облегчение и снова хочу заниматься этой работой'],['partial','Становится легче, но интерес полностью не возвращается'],['gone','Мне по-прежнему не хочется делать саму работу'],['mastery','Я хочу оставить мастерство, но больше не хочу прежнюю роль'],['numb','Я не могу почувствовать ответ — слишком устала']],
 'q4':'В каком профессиональном действии ты чаще всего забываешь смотреть на часы?','q4h':'Выбери максимум два','q4o':[['create','Создаю новое'],['explain','Объясняю сложное и нахожу точные слова'],['direct','Определяю направление'],['connect','Соединяю людей и идеи'],['solve','Решаю нестандартную проблему'],['reveal','Помогаю другому увидеть возможность'],['system','Создаю систему'],['experience','Превращаю замысел в осязаемый опыт'],['none','Сейчас ни в одном']],
 'q5':'Если профессиональная глава изменится, что будет труднее всего потерять?','q5o':[['income','Предсказуемый доход'],['status','Признание и статус'],['competence','Ощущение «я компетентна»'],['belonging','Принадлежность к профессиональному миру'],['influence','Влияние и доступ к важным решениям'],['structure','Понятную структуру жизни'],['investment','Смысл уже вложенных лет'],['image','Образ себя как успешного человека']],
 'q5b':'Что ты чаще всего делаешь, когда думаешь о переменах?','q5bo':[['research','Собираю ещё больше информации'],['fantasy','Представляю резкий уход, но ничего не проверяю'],['minimize','Убеждаю себя, что всё не так плохо'],['improve','Пытаюсь улучшить нынешнюю роль'],['talk','Обсуждаю перемены, но не создаю внешнюю пробу'],['testing','Уже делаю небольшие реальные пробы']],
 'q6':'Три источника могут говорить разное. Что сообщает каждый сейчас?','mind':'Мышление говорит','mindo':[['stay','остаться'],['redesign','пересобрать'],['leave','уйти'],['wait','пока не решать']], 'body':'Тело расслабляется при мысли','bodyo':[['stay','остаться'],['redesign','пересобрать'],['other','попробовать другое'],['none','ни при одном варианте']], 'behavior':'Фактическое поведение показывает','behavioro':[['current','я инвестирую в нынешнюю главу'],['alternatives','я создаю альтернативы'],['delay','я откладываю оба направления']],
 'comment':'Если хочешь, добавь одну фразу: что ещё важно не потерять из виду?','commentph':'Необязательно. Максимум одна короткая мысль.','result_label':'Возможное прочтение твоих ответов','result_title':'Transition Insight','result_intro':'Не истина о тебе, а гипотеза, созданная из сочетания сигналов. Оставь только то, что действительно резонирует.','came':'С каким вопросом ты пришла','reframe':'Где может находиться настоящая развилка','unseen':'Что ты можешь не замечать','evidence':'Три сигнала, на которых основано прочтение','alternative':'Альтернативное прочтение','unknown':'Что пока нельзя заключить','experiment':'Эксперимент, который различит две гипотезы','observe':'Что наблюдать','print':'Сохранить / распечатать','copy':'Скопировать','again':'Пройти с другим вопросом','copied':'Скопировано','gateway':'Продолжить в Gateway','home':'На главную','footer':'Cosmos Luminosity · The Thoughtful Transition'
},
'en':{
 'layout':'default-en','file':'page-next-chapter-experiment-en.hbs','lang':'en','url':'https://www.cosmosluminosity.com/next-chapter-experiment-en/','other':'https://www.cosmosluminosity.com/next-chapter-experiment/',
 'title':'What might you be missing in your professional transition?','page':'Discern Your Professional Transition — Cosmos Luminosity','desc':'A brief investigation: one non-obvious pattern, its evidence, and an experiment before a major professional decision.','eyebrow':'A free investigation · 4–6 minutes','lead':'Answer a few precise questions. You will receive not a summary, but a possible reading of what connects your answers.','meta':'No sign-up · almost no writing · answers stay in your browser','start':'Reveal a possible pattern','note':'This is not a personality test, diagnosis, or decision made for you. The interpretation remains a hypothesis to test in real life.','back':'Back','next':'Continue','result_btn':'Show my reading','required':'Choose an answer to continue.','limit':'Choose no more than two options.','steps':['Question','Tension','Contrast','Alive','Holding','Divergence'],
 'q1':'Which question is closest to yours right now?','q1o':[['leave','I am considering leaving my profession'],['role','I want a different role but cannot see which one'],['way','I no longer consent to working in the same way'],['notmine','Externally everything is fine, but inwardly it is no longer mine'],['next','I sense a next chapter but cannot see its shape']],
 'q2':'When does resistance become strongest?','q2h':'Choose up to two','q2o':[['rescue','When I have to rescue the situation again'],['available','When I must remain permanently available'],['stagnant','When I repeat familiar work without growth'],['noagency','When decisions happen without my influence'],['oldself','When I have to perform an earlier version of myself'],['meaningless','When the outcome no longer feels meaningful'],['even_good','Even when conditions are good and pressure is low']],
 'q3':'Imagine income is protected, the team fits, the pace is calmer, and boundaries are respected. What happens inside?','q3o':[['returns','I feel relief and want to do the work again'],['partial','It becomes easier, but interest does not fully return'],['gone','I still do not want to do the work itself'],['mastery','I want to keep the mastery, but not the former role'],['numb','I cannot feel an answer—I am too depleted']],
 'q4':'In which professional action do you most often forget to check the time?','q4h':'Choose up to two','q4o':[['create','Creating something new'],['explain','Explaining complexity and finding precise language'],['direct','Determining direction'],['connect','Connecting people and ideas'],['solve','Solving a non-standard problem'],['reveal','Helping another person see a possibility'],['system','Building a system'],['experience','Turning an idea into a tangible experience'],['none','None at the moment']],
 'q5':'If this professional chapter changed, what would be hardest to lose?','q5o':[['income','Predictable income'],['status','Recognition and status'],['competence','The feeling that I am competent'],['belonging','Belonging to a professional world'],['influence','Influence and access to important decisions'],['structure','A clear structure for life'],['investment','Meaning in the years already invested'],['image','My image of myself as successful']],
 'q5b':'What do you most often do when you think about change?','q5bo':[['research','Collect even more information'],['fantasy','Imagine a dramatic exit but test nothing'],['minimize','Persuade myself it is not that bad'],['improve','Try to improve the current role'],['talk','Discuss change but create no external prototype'],['testing','Already run small real-world tests']],
 'q6':'Three sources may disagree. What is each saying now?','mind':'My mind says','mindo':[['stay','stay'],['redesign','redesign'],['leave','leave'],['wait','do not decide yet']], 'body':'My body relaxes at the thought of','bodyo':[['stay','staying'],['redesign','redesigning'],['other','trying something else'],['none','none of the options']], 'behavior':'My actual behaviour shows','behavioro':[['current','I invest in the current chapter'],['alternatives','I create alternatives'],['delay','I postpone both directions']],
 'comment':'If you wish, add one sentence: what else should not be overlooked?','commentph':'Optional. One short thought at most.','result_label':'A possible reading of your answers','result_title':'Transition Insight','result_intro':'Not a truth about you, but a hypothesis created from the relationship between signals. Keep only what genuinely resonates.','came':'The question you arrived with','reframe':'Where the real decision may sit','unseen':'What you may not be noticing','evidence':'Three signals behind this reading','alternative':'An alternative reading','unknown':'What cannot yet be concluded','experiment':'An experiment that distinguishes the hypotheses','observe':'What to observe','print':'Save / print','copy':'Copy','again':'Explore another question','copied':'Copied','gateway':'Continue into Gateway','home':'Return home','footer':'Cosmos Luminosity · The Thoughtful Transition'
}}

def choices(name,items,multi=False):
 t='checkbox' if multi else 'radio'
 return ''.join(f'<label class="quick-choice"><input type="{t}" name="{name}" value="{v}"><span>{escape(x)}</span></label>' for v,x in items)
def screen(n,title,body,hint=''):
 return f'<fieldset class="quick-step" data-step="{n}" hidden><legend><span>0{n}</span>{escape(title)}</legend>{f"<p class=quick-hint>{escape(hint)}</p>" if hint else ""}{body}<p class="quick-error" data-error></p></fieldset>'
def out(k,label,cls=''):
 return f'<section class="insight-block {cls}"><h3>{escape(label)}</h3><div data-out="{k}"></div></section>'

def build(c):
 gateway='/gateways/' if c['lang']=='ru' else '/en/gateways/'; home='/' if c['lang']=='ru' else '/en/'
 p=[f'{{{{!< {c["layout"]}}}}}',f'{{{{#contentFor "page_title"}}}}{c["page"]}{{{{/contentFor}}}}',f'{{{{#contentFor "page_description"}}}}{c["desc"]}{{{{/contentFor}}}}',f'{{{{#contentFor "canonical_url"}}}}{c["url"]}{{{{/contentFor}}}}',f'{{{{#contentFor "ru_url"}}}}https://www.cosmosluminosity.com/next-chapter-experiment/{{{{/contentFor}}}}',f'{{{{#contentFor "en_url"}}}}https://www.cosmosluminosity.com/next-chapter-experiment-en/{{{{/contentFor}}}}','<link rel="stylesheet" href="{{asset "css/quick-transition.css"}}">',f'<div class="quick-experience" data-quick-transition data-version="4" lang="{c["lang"]}">']
 p.append(f'<section class="quick-hero"><div class="quick-hero-inner"><p class="eyebrow">{c["eyebrow"]}</p><h1>{c["title"]}</h1><p class="quick-lead">{c["lead"]}</p><p class="quick-meta">{c["meta"]}</p><button type="button" class="quick-button primary" data-start>{c["start"]}</button><p class="quick-note">{c["note"]}</p></div><div class="quick-signal" aria-hidden="true"><i></i><i></i><i></i></div></section>')
 p.append('<section class="quick-workspace" data-workspace hidden><nav class="quick-progress" aria-label="Progress"><ol>'+''.join(f'<li data-progress="{i}"><span>{i}</span><b>{x}</b></li>' for i,x in enumerate(c['steps'],1))+'</ol><i data-bar></i></nav><form data-form novalidate>')
 p.append(screen(1,c['q1'],f'<div class="quick-choices">{choices("entry",c["q1o"])}</div>'))
 p.append(screen(2,c['q2'],f'<div class="quick-choices">{choices("tension",c["q2o"],True)}</div>',c['q2h']))
 p.append(screen(3,c['q3'],f'<div class="quick-choices">{choices("contrast",c["q3o"])}</div>'))
 p.append(screen(4,c['q4'],f'<div class="quick-choices">{choices("alive",c["q4o"],True)}</div>',c['q4h']))
 p.append(screen(5,c['q5'],f'<div class="quick-choices">{choices("loss",c["q5o"])}</div><h2 class="quick-subquestion">{escape(c["q5b"])}</h2><div class="quick-choices">{choices("strategy",c["q5bo"])}</div>'))
 tri=f'<div class="signal-grid"><section><h2>{c["mind"]}</h2>{choices("mind",c["mindo"])}</section><section><h2>{c["body"]}</h2>{choices("body",c["bodyo"])}</section><section><h2>{c["behavior"]}</h2>{choices("behavior",c["behavioro"])}</section></div><label class="quick-comment"><span>{c["comment"]}</span><textarea name="comment" rows="2" maxlength="240" placeholder="{c["commentph"]}"></textarea></label>'
 p.append(screen(6,c['q6'],tri))
 p.append(f'<div class="quick-nav"><button class="quick-button" type="button" data-back hidden>{c["back"]}</button><button class="quick-button primary" type="button" data-next>{c["next"]}</button></div></form>')
 p.append(f'<section class="quick-result" data-result hidden aria-live="polite"><header class="result-heading"><p class="eyebrow">{c["result_label"]}</p><h2>{c["result_title"]}</h2><p>{c["result_intro"]}</p></header><article class="insight-sheet" data-sheet><header class="insight-cover"><span>COSMOS LUMINOSITY</span><h2>Transition<br>Insight</h2><p>One pattern · Two readings · One experiment</p></header><div class="insight-body">')
 p += [out('came',c['came']),out('reframe',c['reframe'],'hero-block'),out('unseen',c['unseen'],'unseen'),out('evidence',c['evidence']),out('alternative',c['alternative']),out('unknown',c['unknown']),out('experiment',c['experiment'],'experiment'),out('observe',c['observe'])]
 p.append(f'</div><footer>{c["footer"]}</footer></article><div class="result-actions"><button class="quick-button primary" type="button" data-print>{c["print"]}</button><button class="quick-button" type="button" data-copy>{c["copy"]}</button><button class="quick-button quiet" type="button" data-restart>{c["again"]}</button></div><p data-copy-status role="status"></p><div class="result-next"><a class="quick-button primary" href="{gateway}">{c["gateway"]}</a><a class="quick-button" href="{home}">{c["home"]}</a></div></section></section></div>')
 p.append('<script>window.QUICK_COPY='+json.dumps(c,ensure_ascii=False).replace('</','<\\/')+';</script><script src="{{asset "js/quick-transition.js"}}" defer></script>')
 return '\n'.join(p)+'\n'

for c in D.values():(T/c['file']).write_text(build(c))
print('quick transition templates v4 written')
