from __future__ import annotations

from typing import TYPE_CHECKING, Dict

if TYPE_CHECKING:
    from pathlib import Path


option_keys = {
    "UnicodeKeyboard": "dword",
    "ChartAutoActivateCodepage": "dword",
    "UnicodeRangePercent": "dword",
    "AutoAlignVector": "dword",
    "ContourSnapAllPoints": "dword",
    "ShowMeterPanel": "dword",
    "FontLabNodes": "dword",
    "EditDeleteAlt": "dword",
    "ControlSwitch": "dword",
    "RemoveZeroKerning": "dword",
    "EditAutoSelectLayers": "dword",
    "SyncronizeMasters": "dword",
    "EditComponentsByOutline": "dword",
    "EditLayersExpanded": "dword",
    "EditKeyboardEditBCP": "dword",
    "EditShowMasterPoints": "dword",
    "EditConnectMasters": "dword",
    "EditShowMeasurementLine": "dword",
    "EditUndoSelection": "dword",
    "EditShowNodesSelection": "dword",
    "MaskMetrics": "dword",
    "EditEditSelection": "dword",
    "EditDoubleClickBitmap": "dword",
    "EditDoubleClickMask": "dword",
    "EditBCPsFixed": "dword",
    "EditPreviewKey": "dword",
    "OTPreviewSize": "dword",
    "OTSampleSize": "dword",
    "EditNotFillOpen": "dword",
    "OptimizeAlign": "dword",
    "OptimizeReduce": "dword",
    "UnicodeStrings": "dword",
    "DuplicateX": "dword",
    "DuplicateY": "dword",
    "PasteX": "dword",
    "PasteY": "dword",
    "Shift10": "dword",
    "MetricsBottomBar0": "dword",
    "MetricsShowTable0": "dword",
    "MetricsShowBar0": "dword",
    "MetricsBarExpanded0": "dword",
    "MetricsBottomBar1": "dword",
    "MetricsShowTable1": "dword",
    "MetricsShowBar1": "dword",
    "MetricsBarExpanded1": "dword",
    "MetricsBottomBar2": "dword",
    "MetricsShowTable2": "dword",
    "MetricsShowBar2": "dword",
    "MetricsBarExpanded2": "dword",
    "MetricsBottomBar3": "dword",
    "MetricsShowTable3": "dword",
    "MetricsShowBar3": "dword",
    "MetricsBarExpanded3": "dword",
    "FontExpanded": "dword",
    "AutoRemoveHints": "dword",
    "OTAddClasses": "dword",
    "OTAddMetricsClasses": "dword",
    "OTWriteGDEF": "dword",
    "OTWriteMort": "dword",
    "OTReadMort": "dword",
    "OTGenerate": "dword",
    "OTCompileFeatures": "dword",
    "OTOldContextRule": "dword",
    "TTIReadKernFeature": "dword",
    "TTIGenerateNames": "dword",
    "TTEWriteKernFeature": "dword",
    "TTEWriteKernTable": "dword",
    "TTESmartMacNames": "dword",
    "TTESmartFontName": "dword",
    "TTEVersionOS2": "dword",
    "TTEExportOT": "dword",
    "TTEExportVOLT": "dword",
    "TTIReadOT": "dword",
    "TTIReadBinaryOT": "dword",
    "TTIStoreBinaryOT": "dword",
    "TTToolReverseShift": "dword",
    "TTEWriteBitmaps": "dword",
    "TTIReadBitmaps": "dword",
    "CopyHDMXData": "dword",
    "TracerCurves": "dword",
    "TracerExtremePoints": "dword",
    "TracerTolerance": "dword",
    "TracerStraightenAngle": "dword",
    "TracerPresetMode": "dword",
    "TracerCurveFit": "dword",
    "TTIFontNames": "dword",
    "TTEFontNames": "dword",
    "BitmapSize": "dword",
    "ColorBackground": "dword",
    "ColorBackgroundMask": "dword",
    "ColorBackgroundMetrics": "dword",
    "ColorForegroundMetrics": "dword",
    "ColorMaskPen": "dword",
    "ColorClosepath": "dword",
    "ColorSeacPen": "dword",
    "ColorHintsPen": "dword",
    "ColorTemplate": "dword",
    "ColorOutline": "dword",
    "ColorBitmap": "dword",
    "ColorVMetrics": "dword",
    "ColorMetrics": "dword",
    "ColorEcho": "dword",
    "ColorGrid": "dword",
    "ColorGuide": "dword",
    "ColorGlobalGuide": "dword",
    "ColorGroups": "dword",
    "ColorNeighbors": "dword",
    "StyleInactiveMetrics": "dword",
    "StyleMetrics": "dword",
    "SamplePPM1": "dword",
    "SamplePPM2": "dword",
    "HideAllLayers": "dword",
    "CustomMarkColor": "dword",
    "QuickZoomScale": "dword",
    "TrackingMode": "dword",
    "TrackingDistance": "dword",
    "FitAscender": "dword",
    "FitDescender": "dword",
    "EraseSize": "dword",
    "ClosepathArrowLen": "dword",
    "DefaultGlyph": "dword",
    "GlyphNameSortMode": "dword",
    "EditBitmapStyle": "dword",
    "EditZoomMode": "dword",
    "EditHitDistance": "dword",
    "EditChangeCursor": "dword",
    "EditHandleTool": "dword",
    "EditBCVOpacity": "dword",
    "EditFollowScroll": "dword",
    "EditLeaveEcho": "dword",
    "EditInstantRefresh": "dword",
    "EditShowSelection": "dword",
    "EditShowAnchorNames": "dword",
    "EditSmoothOutline": "dword",
    "EditAllSmooth": "dword",
    "EditSmallNodes": "dword",
    "EditThickOutline": "dword",
    "EditShowCross": "dword",
    "EditScaleEPS": "dword",
    "MMExtrapolation": "dword",
    "EditShowPosition": "dword",
    "HideToolbars": "dword",
    "AutoMetricsLeft": "dword",
    "AutoMetricsRight": "dword",
    "AutoMetricsClose": "dword",
    "AutohintingMinHLen": "dword",
    "AutohintingMinVLen": "dword",
    "AutohintingMinHWidth": "dword",
    "AutohintingMinVWidth": "dword",
    "AutohintingMaxHWidth": "dword",
    "AutohintingMaxVWidth": "dword",
    "AutohintingRemoveHints": "dword",
    "AutohintingEngine": "dword",
    "CreateUnexistingCharacters": "dword",
    "AutohintingHRatio": "str",
    "AutohintingVRatio": "str",
    "PaintTextFont": "str",
    "PreviewPointSize": "str",
    "PreviewPPMs": "str",
    "PreviewPPMsExpanded": "str",
    "PreviewExpandedHeight": "dword",
    "PreviewWidth": "dword",
    "PreviewSmooth": "dword",
    "PreviewExpanded": "dword",
    "PreviewBlueColor": "dword",
    "PreviewHighlightKeyGlyphs": "dword",
    "PreviewLockDependences": "dword",
    "PreviewKeepExceptions": "dword",
    "PreviewShowReferences": "dword",
    "PreviewApplyTemplate": "dword",
    "PreviewAutoWrap": "dword",
    "PreviewKerningIcons": "dword",
    "PreviewFocusString": "dword",
    "PreviewPanelTop": "dword",
    "PreviewMode": "dword",
    "PreviewSize": "dword",
    "PreviewSecondLine": "str",
    "VendorCode": "str",
    "ExpandKernFlags": "dword",
    "ExpandKernCount": "dword",
    "ExpandKernCodepage": "str",
    "CacheTTPath": "str",
    "CacheTTUse": "dword",
    "Template_Use": "dword",
    "Template_Path": "str",
    "Template_BDF": "str",
    "DSIG_Use": "dword",
    "DSIG_TimeStamp": "dword",
    "DSIG_SertPath": "str",
    "DSIG_KeyPath": "str",
    "DSIG_Password": "str",
    "FileOpenSample": "str",
    "PreviewAlternativeArrows": "dword",
    "PreviewAutoScroll": "dword",
    "PreviewListWidth": "dword",
    "PreviewFilterKerning": "dword",
    "PreviewFilterMetrics": "dword",
    "PreviewPaintStyle": "dword",
    "PreviewLockStyle": "dword",
    "PreviewSnapStyle": "dword",
    "OverlapMode": "dword",
    "PaintStyleEx": "dword",
    "SnapStyleEx": "dword",
    "LockStyleEx": "dword",
    "EditGridX": "dword",
    "EditGridY": "dword",
    "EditRulers": "dword",
    "EditSmoothIsSmooth": "dword",
    "PaintColor": "dword",
    "PaintTool": "dword",
    "PaintBrushWidth": "dword",
    "PaintBrushRoundness": "dword",
    "PaintBrushBody": "dword",
    "PaintBrushVectorX": "dword",
    "PaintBrushVectorY": "dword",
    "PaintMode": "dword",
    "PaintBrushJoin": "dword",
    "PaintBrushCap": "dword",
    "PaintTracePolygon": "dword",
    "PaintTextSize": "dword",
    "PaintAutoTransform": "dword",
    "PaintAutoView": "dword",
    "PaintReverseBrushAutoColor": "dword",
    "PaintJapanese": "dword",
    "FontAudit": "dword",
    "FontAuditLive": "dword",
    "TTIAutohint": "dword",
    "TTIDecompose": "dword",
    "TTIKeepHints": "dword",
    "TTIConvert": "dword",
    "TTIScale1000": "dword",
    "TTIStoreTables": "dword",
    "TTEStoreTables": "dword",
    "TTECmap10": "dword",
    "EmbeddingType": "dword",
    "TTHHintingOptions": "dword",
    "TTHPPM": "dword",
    "ATMPPM": "dword",
    "TTEExportUnicode": "dword",
    "TTEHint": "dword",
    "TTEAutohint": "dword",
    "TTEKeep": "dword",
    "TTEVisual": "dword",
    "TTEheadBBoxSavings": "dword",
    "TTEApplyBBoxSavings": "dword",
    "TTEAutoWinAscDesc": "dword",
    "PreviewProcessFeatures": "dword",
    "PreviewShowClassMembers": "dword",
    "TTEAddCharacters": "dword",
    "TTENoReorder": "dword",
    "TTESubrize": "dword",
    "TTEDecompose": "dword",
    "T1Terminal": "dword",
    "AutoSave": "dword",
    "AutoSaveTick": "dword",
    "ChartShowNotes": "dword",
    "ChartSorting": "dword",
    "ChartDragDrop": "dword",
    "GroupKerning": "dword",
    "GroupFill": "dword",
    "GroupShapeFill": "dword",
    "GroupMask": "dword",
    "GroupShapeMask": "dword",
    "GroupShapeOpacity": "dword",
    "GroupUseMetrics": "dword",
    "GroupCenter": "dword",
    "GroupDoubleClick": "dword",
    "GroupShiftX": "dword",
    "GroupShiftY": "dword",
    "T1Sort": "dword",
    "T1UseOTFamilyName": "dword",
    "T1UseOTStyleName": "dword",
    "T1Encoding": "dword",
    "T1Decompose": "dword",
    "T1MatchEncoding": "dword",
    "T1PFM": "dword",
    "T1AFM": "dword",
    "T1FSType": "dword",
    "T1Autohint": "dword",
    "T1Unicode": "dword",
    "T1UseOS2": "dword",
    "T1UseTrademarkName": "dword",
    "T1ExportEncoding": "dword",
    "CodepagesCount": "dword",
    "OpenOutput": "dword",
    "Backup": "dword",
    "ChartUseTemplate": "dword",
    "ChartCopyKerning": "dword",
    "GlyphsBarOpen": "dword",
    "GlyphsBarTop": "dword",
    "ChartDoubleClick": "dword",
    "ChartAutoHide": "dword",
    "ChartPreviewMarks": "dword",
    "ChartSampleSize": "dword",
    "ChartStyle": "dword",
    "ChartCaptionFontSize": "dword",
    "ChartTemplateFontSize": "dword",
    "ChartCaptionFontCharSet": "dword",
    "ChartTemplateFontCharSet": "dword",
    "ChartGenerate": "dword",
    "ChartGenerateRTL": "dword",
    "ChartAutoUnicode": "dword",
    "ChartApplyTemplate": "dword",
    "ChartCaptionFontName": "str",
    "ChartTemplateFontName": "str",
    "FontSmallName": "str",
    "FontSmallSize": "dword",
    "FontDialogName": "str",
    "FontDialogSize": "dword",
    "FontRulerName": "str",
    "FontRulerSize": "dword",
    "FontPanelName": "str",
    "FontPanelSize": "dword",
    "FontTableName": "str",
    "FontTableSize": "dword",
    "FontFixedName": "str",
    "FontFixedSize": "dword",
    "T1ExportCompatibleCyrillic": "dword",
    "OutputFontName": "str",
    "MacroFontName": "str",
    "CustomDict": "str",
    "EnablePython": "dword",
    "EnableExtPythonEditor": "dword",
    "ExtPythonEditor": "str",
    "EnableTooltips": "dword",
    "EnableStickPanels": "dword",
    "ATMScaler": "dword",
    "ATMSmooth": "dword",
    "TTFScaler": "dword",
    "TTFSmooth": "dword",
}


def parse_registry_file(file_path: Path) -> Dict[str, Dict[str, str | int | float]]:
    with open(file_path, "r") as f:
        data = f.read()

    reg = {}
    lines = data.splitlines()
    if not lines:
        raise EOFError

    assert lines[0] == "Windows Registry Editor Version 5.00"

    key = None
    values = {}

    for line in lines[1:]:
        if line == "":
            continue

        if line.startswith("[") and line.endswith("]"):
            if key:
                reg[key] = values
            key = line.strip("[]")
            values = {}

        elif line.startswith('"') and '"=' in line:
            k, v = line.split("=", 1)
            values[k.strip('"')] = v

        else:
            print("Unhandled line in registry file:")
            print(line)
            raise ValueError

    if key:
        reg[key] = values

    # We now have a dict where the keys may be unknown, and the values are in raw format

    parsed = {}

    reg_options = reg.get(r"HKEY_CURRENT_USER\Software\FontLab\FontStudio 5\Options")
    if reg_options is None:
        print("Could not find data section in registry file")
        raise ValueError

    for key, val_type in option_keys.items():
        if key not in reg_options:
            continue

        if val_type == "dword":
            hex_str = reg_options[key].split(":", 1)[1]
            assert len(hex_str) == 8
            val = int(hex_str, 16)

        elif val_type == "str":
            s = reg_options[key]
            assert s.startswith('"')
            assert s.endswith('"')
            val = reg_options[key][1:-1]

        else:
            print(f"Unhandled registry value type {val_type}")
            raise ValueError

        parsed[key] = val

    return parsed
