from pathlib import Path
import base64,mimetypes,re
root=Path(__file__).resolve().parents[1]
html=(root/'index.html').read_text(encoding='utf-8')
css_files=['tokens','palettes','base','layout','components','motion','print']
js_files=['data/site-config','data/projects','data/posts','data/translations','state','theme','i18n','ui-demo','projects','lightbox','comments','posts','forms','company','socials','motion','app']
cache={}
def data_uri(rel):
    if rel in cache:return cache[rel]
    path=root/rel
    if not path.exists():return rel
    mime=mimetypes.guess_type(path.name)[0] or 'application/octet-stream'
    cache[rel]=f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode()}"
    return cache[rel]
def inline_paths(text):
    return re.sub(r'assets/img/[A-Za-z0-9_./-]+\.(?:svg|png|jpg|jpeg|webp)',lambda m:data_uri(m.group(0)),text)
combined_css='\n'.join((root/f'assets/css/{n}.css').read_text(encoding='utf-8') for n in css_files)
combined_js='\n'.join((root/f'assets/js/{n}.js').read_text(encoding='utf-8') for n in js_files)
combined_js=inline_paths(combined_js);html=inline_paths(html)
for n in css_files:html=re.sub(rf'\s*<link rel="stylesheet" href="assets/css/{re.escape(n)}\.css">','',html)
html=html.replace('</head>',f'<style>{combined_css}</style></head>',1)
for n in js_files:html=re.sub(rf'\s*<script src="assets/js/{re.escape(n)}\.js" defer></script>','',html)
html=html.replace('</body>',f'<script>{combined_js}</script></body>',1)
html=re.sub(r'\s*<link rel="(?:icon|apple-touch-icon|manifest)"[^>]*>','',html)
(root/'standalone.html').write_text(html,encoding='utf-8')
print('Standalone preview created at standalone.html')
