import re
import sys
import pathlib
import datetime
from pprint import pprint


if len(sys.argv) < 2:
    print('Generate rcc.c file from file containing SystemClock_Config function\n')
    print(f'Usage: {sys.argv[0]} <file.c>')
    sys.exit(0)

t = pathlib.Path(sys.argv[1]).read_text()

if not re.search(r'void\s+SystemClock_Config\s*\(\s*void\s*\).*\{', t, re.M | re.S):
    print('/* !!! Warning, SystemClock_Config not found !!!\n'
          '   Use under your own risk */')

it = re.finditer(r'^\s+(?:RCC_|Periph)\w+InitStruct.*?=[\s\S]*?;', t, re.M)
ldo_supply = re.search(r'\bHAL_PWREx_ConfigSupply\s*\(([\w_][\w\d_]*)\)\s*\;', t)
v_scale = re.search(r'\b__HAL_PWR_VOLTAGESCALING_CONFIG\s*\(([\w_][\w\d_]*)\)\s*\;', t)
f_latency = re.search(r'\bHAL_RCC_ClockConfig\s*\(.*?\,\s*([\w_][\w\d_]*)\s*\)', t)

l = [re.sub(r'[\s\n\r]+', ' ', m[0]).replace(';', '').strip() for m in it]
ll = [[x.strip() for x in e.split('=')] for e in l]


def mk_parts(d, parts, val):
    if len(parts) == 1:
        d[parts[0]] = val
    else:
        if parts[0] not in d:
            d[parts[0]] = {}
        mk_parts(d[parts[0]], parts[1:], val)


d = {}
for k, v in ll:
    parts = k.split('.')
    mk_parts(d, parts, v)


def print_dict(d, ident=4):
    for k, v in d.items():
        if type(v) is dict:
            print(' '*ident + f'.{k} = {{')
            print_dict(v, ident + 4)
            print(' '*ident + '},')
        else:
            print(' '*ident + f'.{k} = {v},')


print(f'''/* Autogenerated file at {datetime.datetime.today()} */

#include "rcc.h"

RCC_SECTION const rcc_init_t rcc = {{
    .flashLatency = {f_latency[1]},
    .voltageScale = {v_scale[1]},
    .configSupply = {ldo_supply[1]},
''', end='')
print_dict(d)
print('};\n')
