import os
import re

# Directory with the font files
directory = './'

# Get list of font files
font_files = os.listdir(directory)

# Initialize an empty list for the typefaces
typefaces = []

# Loop over the font files
for file in font_files:
    # Strip the file extension
    name_weight, extension = os.path.splitext(file)
    
    # Only process .ttf, .otf, .woff and .woff2 files
    if extension.lower() not in ['.ttf', '.otf', '.woff', '.woff2']:
        continue
    
    # Split the name and weight
    match = re.match(r'(.*)_(\d+)(I)?', name_weight)
    if match:
        name, weight, is_italic = match.groups()
    else:
        name = name_weight
        weight = "400"
        is_italic = None
    
    # Check if the typeface is already in the list
    for typeface in typefaces:
        if typeface['name'] == name:
            break
    else:
        # If the typeface is not in the list, add a new one
        typeface = {
            "name": name,
            "fonts" : [],
            "tags" : ["sans-serif"],
        }
        typefaces.append(typeface)
    font_descriptor = weight + ('i' if is_italic else '')
    typeface['fonts'].append(font_descriptor)

# Convert the typefaces list to a JavaScript object string
typefaces_js = '[\n' + ',\n'.join(
    f'    {typeface["name"].lower()} : ' + 
    '{\n' +
    f'        "name": "{typeface["name"]}",\n' +
    '        "fonts" : [\n' +
    ',\n'.join(
        f'            "{font_descriptor}"'
        for font_descriptor in typeface['fonts']
    ) +
    '\n        ],\n' +
    '        "tags" : ["sans-serif"],\n' +
    '        "link" : "",\n' +
    '    }'
    for typeface in typefaces
) + '\n]'

typefaces = sorted(typefaces, key=lambda k: k['name'])

# Write the JavaScript object
with open('01_object.js', 'w') as f:
    f.write('typeFaces = {\n')

    for typeface in typefaces:
        f.write(f'    {typeface["name"].lower()} : {{\n')
        f.write(f'        "name": "{typeface["name"]}",\n')
        f.write(f'        "fonts": [\n')
        for font in typeface['fonts']:
            f.write(f'            "{font}",\n')
        f.write(f'        ],\n')
        f.write(f'        "tags": ["sans-serif"],\n')
        f.write(f'        "link": "",\n')
        f.write(f'        "creator": "",\n')
        f.write(f'        "creatorLink": "",\n')
        f.write(f'        "licence": "",\n')
        f.write(f'        "commercial": false,\n')
        f.write(f'        "open": false,\n')
        f.write(f'    }},\n')
        
    f.write('};')