import win32com.client as win32
import os

def convert_excel_to_vba(EXCEL_FILPATH):
    excel = win32.Dispatch("Excel.Application")
    excel.Visible = False
    excel.DisplayAlerts = False

    full_path = os.path.abspath(EXCEL_FILPATH)
    wb = excel.Workbooks.Open(full_path)

    vbproj = wb.VBProject

    # ---- Inject ThisWorkbook Code ----

    code = r'''
    Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
        If Target.Column = 11 And Target.Cells.Count = 1 Then
            On Error Resume Next
            Dim cellNote As String
            Dim pdfPath As String
            Dim pageNumber As String
            Dim chromeCommand As String
            If Not Target.Comment Is Nothing Then
                cellNote = Target.Comment.Text
                If InStr(cellNote, ".pdf#page=") > 0 Then
                    Dim parts() As String
                    parts = Split(cellNote, "#page=")
                    pdfPath = Replace(parts(0), "\", "/")
                    pageNumber = parts(1)
                    
                    chromeCommand = """C:\Program Files\Google\Chrome\Application\chrome.exe"" ""file:///" & pdfPath & "#page=" & pageNumber & """"
                    CreateObject("WScript.Shell").Run chromeCommand, 1, False
                End If
            ElseIf Sh.Cells(Target.Row, 26).Value <> "" Then
                cellNote = Sh.Cells(Target.Row, 26).Value
                
                If InStr(cellNote, ".pdf#page=") > 0 Then
                    Dim parts2() As String
                    parts2 = Split(cellNote, "#page=")
                    pdfPath = Replace(parts2(0), "\", "/")
                    pageNumber = parts2(1)
                    chromeCommand = """C:\Program Files\Google\Chrome\Application\chrome.exe"" ""file:///" & pdfPath & "#page=" & pageNumber & """"
                    CreateObject("WScript.Shell").Run chromeCommand, 1, False
                End If
            End If
            
            On Error GoTo 0
        End If
    End Sub
    '''

    wb_component = vbproj.VBComponents("ThisWorkbook")
    wb_component.CodeModule.DeleteLines(1, wb_component.CodeModule.CountOfLines)
    wb_component.CodeModule.AddFromString(code)

    # ---- Save as Macro Enabled ----
    new_path = full_path.replace(".xlsx", ".xlsm")
    wb.SaveAs(new_path, FileFormat=52)  # 52 = xlsm
    wb.Close(False)

    excel.Quit()


if __name__ == '__main__':
    EXCEL_FILPATH = "V1_Info_WB_Copy 1 m - Copy - Copy.xlsx"  # Replace with your Excel file path
    convert_excel_to_vba(EXCEL_FILPATH)