#!/usr/bin/env python3


import os
import urllib.request
import json
import html.parser
import textwrap


BASE_URL     = 'https://raw.githubusercontent.com/allo-/firefox-profilemaker'
BRANCH_URL   = f'{BASE_URL}/master'
PROFILES_URL = f'{BRANCH_URL}/profiles'
SETTINGS_URL = f'{BRANCH_URL}/settings'
PROFILE_URL  = f'{PROFILES_URL}/01_default.json'
IGNORE       = ['Addons', 'Enterprise Policies']
COMMENT      = '// '


def get(url):
    with urllib.request.urlopen(url) as response:
        return json.loads(response.read())


def parse(input, wrap=False):
    output = ''
    def parser_handle_data(data):
        nonlocal output
        output += data
    parser = html.parser.HTMLParser()
    parser.handle_data = parser_handle_data
    parser.feed(input)
    if wrap:
        output = textwrap.fill(
            output,
            width=79-len(COMMENT),
            subsequent_indent=COMMENT,
        )
    return output


paragraphs = []
name = os.path.basename(BASE_URL)
paragraphs.append(f'/// {name}')
for category, settings_files in get(f'{PROFILE_URL}')[1].items():
    if category in IGNORE:
        continue
    paragraphs.append(f'//// {category}')
    for settings_file in settings_files:
        for settings in get(f'{SETTINGS_URL}/{settings_file}'):
            lines = []
            label     = settings.get('label')
            help_text = settings.get('help_text')
            choices   = settings.get('choices')
            initial   = settings.get('initial')
            setting   = settings.get('setting')
            config    = settings.get('config')
            comment = '' if initial or choices else COMMENT
            if label:
                label = parse(label)
                lines.append(f'///// {label}')
            if help_text:
                help_text = parse(help_text, True)
                lines.append(f'// {help_text}')
            if choices:
                config = config[initial]
                choice = parse(choices[initial], True)
                lines.append(f'// {choice}')
            if setting:
                config = {setting: initial}
            if config:
                for key, value in config.items():
                    key, value = map(json.dumps, [key, value])
                    lines.append(f'{comment}user_pref({key}, {value});')
            paragraphs.append('\n'.join(lines))
print('\n\n'.join(paragraphs))
