import io, re

src = io.open('src/Main.dc.html', encoding='utf-8').read()

link = re.search(r'<link rel="stylesheet"[^>]*>', src).group(0)
css  = re.search(r'<style>(.*?)</style>', src, re.S).group(1)
body = src.split('</helmet>',1)[1].rsplit('</x-dc>',1)[0].strip()

# The .dc.html artboard is a fixed 1440px canvas because a design canvas needs one.
# The served preview should behave like the real site: section grounds full-bleed,
# content capped by .wrap / .wrapwide. Nothing in the Brand Kit specifies a page width.
body = body.replace('<div style="width:1440px; background:#ffffff;">',
                    '<div style="width:100%; min-width:1180px; background:#ffffff;">', 1)

# scope every selector with .ab-Main ; bare `body` becomes the artboard itself
def scope(block):
    out = []
    for line in block.strip('\n').split('\n'):
        m = re.match(r'^(\s*)([^{}]+?)\s*(\{.*)$', line)
        if not m:
            out.append(line.strip())
            continue
        sels = [s.strip() for s in m.group(2).split(',')]
        new = []
        for s in sels:
            new.append('.ab-Main' if s == 'body' else '.ab-Main ' + s)
        out.append(', '.join(new) + ' ' + m.group(3).strip())
    return '\n'.join(out)

html = '''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Equinox &mdash; Home (Direction A &middot; v2)</title>
%s
<style>
*,*::before,*::after { box-sizing:border-box; }
html,body { margin:0; padding:0; background:#ffffff; }
.stage { overflow-x:auto; }
%s
</style>
</head>
<body>
<div class="stage"><div class="ab-Main" style="width:100%%; margin:0 auto">%s</div></div>
</body>
</html>
''' % (link, scope(css), body)

io.open('home-A-v2.html','w',encoding='utf-8').write(html)
print('bytes', len(html))
