import fontforge
import os

desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
#file_path = os.path.join(desktop, "font_extended_info.csv")
file_path = r'C:\Users\latee\Documents\Lateef\SVN-GIT\PakType\Scripts\glyph_info.csv'

f = fontforge.activeFont()
class_to_num = {"automatic": 0, "baseglyph": 1, "Ligature": 2, "Mark": 3, "Component": 4}

if os.path.exists(file_path):
    with open(file_path, "r") as f_in:
        next(f_in) # Skip header
        for line in f_in:
            name, oldName, uni_str, g_class = line.strip().split(',')
            #fontforge.postNotice("row read", f"{name} {id}")            
            try:

                if oldName in f:
                    #glyph = f[id]
                    glyph = f[oldName]
                    glyph.glyphname = name
                    #glyph.width = int(float(width))
                    glyph.glyphclass = g_class #class_to_num.get(g_class, 0)

                    # Handle multiple Unicodes
                    if uni_str != "None":
                        uni_list = uni_str.split(" ")
                        # Set primary (first one)
                        glyph.unicode = int(uni_list[0], 16)

                        # Set alternates if they exist
                        if len(uni_list) > 1:
                            alt_tuples = []
                            for extra in uni_list[1:]:
                                # Format: (unicode, variation_selector)
                                alt_tuples.append((int(extra, 16), 0))
                            glyph.altuni = tuple(alt_tuples)
                    else:
                        glyph.unicode = -1
                        glyph.altuni = None

            except TypeError:
                # This handles cases where the index is invalid or empty
                fontforge.postNotice("Process Complete", f"Error at index {id}")
                continue

    fontforge.postNotice("Import Complete", "Glyph info, Classes, and Alt-Unicodes updated.")