from pathlib import Path
import re, html

THEME=Path('/opt/cosmosluminosity/content/themes/clean')
source=Path('/home/spazio/new-index-recovered.hbs').read_text()

# Remove old layout declaration and add route-specific metadata/layout.
body=re.sub(r'^\{\{!< default\}\}\n','',source, count=1)
ru_head='''{{!< default}}\n{{#contentFor "page_title"}}Cosmos Luminosity — между прежней и следующей главой{{/contentFor}}\n{{#contentFor "page_description"}}Пространство для перехода между ставшей тесной идентичностью и следующей главой, которая ещё обретает очертания.{{/contentFor}}\n{{#contentFor "canonical_url"}}https://www.cosmosluminosity.com/{{/contentFor}}\n{{#contentFor "ru_url"}}https://www.cosmosluminosity.com/{{/contentFor}}\n{{#contentFor "en_url"}}https://www.cosmosluminosity.com/en/{{/contentFor}}\n'''
en_head='''{{!< default-en}}\n{{#contentFor "page_title"}}Cosmos Luminosity — between who you were and what comes next{{/contentFor}}\n{{#contentFor "page_description"}}A space for the passage between an identity that has become too small and a next chapter still taking shape.{{/contentFor}}\n{{#contentFor "canonical_url"}}https://www.cosmosluminosity.com/en/{{/contentFor}}\n{{#contentFor "ru_url"}}https://www.cosmosluminosity.com/{{/contentFor}}\n{{#contentFor "en_url"}}https://www.cosmosluminosity.com/en/{{/contentFor}}\n'''

def localize_ru(text):
    # Replace visible content of every simple bilingual element with its Russian value.
    pattern=re.compile(r'(<(?P<tag>[a-zA-Z][\w-]*)\b(?P<attrs>[^>]*\bdata-ru="(?P<ru>[^"]*)"[^>]*)>)(?P<inner>[^<]*)(</(?P=tag)>)')
    prev=None
    while prev!=text:
        prev=text
        text=pattern.sub(lambda m:m.group(1)+html.unescape(m.group('ru'))+m.group(6),text)
    return text

ru=localize_ru(body)
en=body
# English route must stay inside /en/ for product and contact pages.
for slug in ('magic-cloud','lumoside','contact','privacy'):
    en=en.replace(f'href="/{slug}/"',f'href="/en/{slug}/"')
# JSON-LD route language/URL.
en=en.replace('"url":"https://www.cosmosluminosity.com/"','"url":"https://www.cosmosluminosity.com/en/"')

(THEME/'index.hbs').write_text(ru_head+ru)
(THEME/'index-en.hbs').write_text(en_head+en)
print('wrote',THEME/'index.hbs',len(ru_head+ru))
print('wrote',THEME/'index-en.hbs',len(en_head+en))
print('markers', 'Когда прежняя жизнь' in (ru_head+ru), 'When your old life' in (en_head+en))
