#! /usr/bin/python3
# usage: path to core.css (from unzipped dsfrvX.Y.Z.zip archive),
# for example python3 extract-colours.py dsfr-1.4.0/dist/core/core.css

import re
import sys

colours = {}

with open(sys.argv[1]) as fd:
    core_content = fd.read()

for colour_name in re.findall('background-alt-(.*):', core_content):
    if colour_name.endswith('-hover') or colour_name.endswith('-active'):
        continue
    if colour_name.startswith('-'):
        continue
    colours[colour_name] = {}

for colour_name in colours.keys():
    varname1 = re.findall(r'--background-contrast-%s: var\((.*)\)' % colour_name, core_content)[0]
    varname2 = re.findall(r'--border-default-%s: var\((.*)\)' % colour_name, core_content)[0]
    varname3 = re.findall(r'--background-alt-%s: var\((.*)\)' % colour_name, core_content)[0]

    colours[colour_name]['background-contrast'] = re.findall(r'%s: (#.*);' % varname1, core_content)[0]
    colours[colour_name]['border-default'] = re.findall(r'%s: (#.*);' % varname2, core_content)[0]
    colours[colour_name]['background-alt'] = re.findall(r'%s: (#.*);' % varname3, core_content)[0]

with open('_colours.scss', 'w') as fd:
    print('# generated by extract-colours.py, do not edit.', file=fd)
    print('$dsfr-colours: (', file=fd)
    for colour_name in sorted(colours.keys()):
        print(
            '  %s: (background-contrast: %s, border-default: %s, background-alt: %s),'
            % (
                colour_name,
                colours[colour_name]['background-contrast'],
                colours[colour_name]['border-default'],
                colours[colour_name]['background-alt'],
            ),
            file=fd,
        )
    print(')', file=fd)
