"""
Created By: Jap-Slappa
Date: 29th/May/2026

* VSC-Open-With... My DS918-HTML-Start-Page v2.0
Open Project Folder + wanted files

**********
** v1.0 **
**********

Add this into all VScode settings File
So I don't get the... **Import could not be resolved** warning
"python.analysis.extraPaths": [
        "C:\\My_Python_Helper_Modules"
    ]
"""

from pathlib import Path
import subprocess
import traceback
import sys
import os
import time

# import Mod_01_Get_My_class_Attrs as Get_My_class_Attrs
# import App_Utils.Error_Handling as Error_Handlers

# Tell Python to look in your C-Drive helper folder
# Use raw strings (r"...") to handle Windows backslashes properly
sys.path.append(r"C:\My_Python_Helper_Modules")

# Now you can import your module just like normal
import Mod_01_Get_My_class_Attrs as Get_My_class_Attrs


#? ===============================================================================================
#ANCHOR: my_custom_error( ) 
def basic_custom_error():
    """Print Minimal Custom info about basic Python stack trace
    ---
    Code Example:
        >>> except:
            my_custom_error()
    ---
    NOTE: Module Name or Function name where the error occurred...
        | Are NOT required, as ARGs - Nor Provided at print-out!
    """    
    print()
    print(' =============  An exception occurred  =============')
    print(' =================================================== ')
    traceback.print_exc(limit=1, file=sys.stdout)
    print(' =================================================== ')
    print()
    time.sleep(2.0)


######################################################################

def open_files_in_vscode(vscode_exe_path: str, files_to_open: list):
    """
    Opens a list of files and folders in a specific portable VS Code instance using pathlib.
    """
    #^ 1. Convert the string path to a Path object
    # .resolve() turns it into an absolute path
    vscode_exe = Path(vscode_exe_path).resolve()

    #^ 2. Check if VS Code exists using .exists()
    if not vscode_exe.exists():
        print(f"Error: VS Code PATH Does NOT Exist at: \n{vscode_exe}")
        return

    #^ 3. Prepare the command list starting with the executable
    # We convert the exe to a string because subprocess needs strings, not Path objects
    command = [str(vscode_exe)]

    #^ 4. LOOP-To.. Process each file path
    for file_item in files_to_open:
        # Convert input to a Path object
        # Then .resolve() turns it into an absolute path (removes .. or .)
        file_path = Path(file_item).resolve() 

        # Check if the file exists using .is_file()
        if file_path.exists():
            
            # Convert the PathLib Path Object into string so subprocess can read it
            command.append(str(file_path))
        else:
            print(f"Skipping: {file_path} (File or Folder not found)")

    #^ 5. Launch VS Code With My Selected Files
    if len(command) > 1:
        try:
            #todo: [CMD Window Complete Fix!] for ALL VSC Portables!
            #todo: FIX.. Windows-specific flag to prevent subprocess from opening a new CMD window
            #todo: But adding my CMD Pause function can still does it's job, if needed for debugging
            CREATE_NO_WINDOW = 0x08000000
            
            print(f"DEBUG: Launching executable from: \n >>{os.path.abspath(vscode_exe_path)}")
            print("")
            #^ ===== Launch: VScode Portable + Wanted Files =====
            subprocess.Popen(command, 
                            creationflags=CREATE_NO_WINDOW,
                            stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL,
                            stdin=subprocess.DEVNULL
                            )
            #^ ===== Launch: VScode Portable + Wanted Files =====

            print(f"Successfully launched VS Code For My "
                    f"{VSCODE_PORTABLE_NAME} with {len(command)-1} files.")
        except Exception as Error:
            print(f"Failed to launch: {Error}")
            basic_custom_error()
    else:
        print("No valid files were provided to open.")
#? === End Of Function ===

# ANCHOR: = pause_cmd =
# todo: THIS WORKS!!!
def pause_cmd():
    """
    Stop the CMD wind closing when a a script finishes
    ---
    - The CMD window will automatically close when a script is finished.
        - But I want to see the completed output from the CMD window.
    ---
    To stop this, the "Pause" command is sent to the current CMD window. \n
    The "Pause" command forces CMD to wait for the user to press any key to continue... \n
    ..Then the CMD window will close
    """
    #^ NOTE: in THIS script...
    #^ NOTE: this function will show + pause the CMD window which this script is ran from
    #^ NOTE: Closing the CMD window for this script will also close the VScode Portable
    try:
        #! ===== OS.System =====
        # Stops the CMD window closing after all the tasks are complete
        os.system("pause")
    except Exception as Error:
        print('===== ERROR =====')
        print('===== Pause CMD =====')
        print(f"Error: {Error}")
        basic_custom_error()
#? === End Of Function ===


class Code_Paths():
    Sub_Text        = r'G:\Data 10 - VScode\# 2024\(2024)-Vs_Code_4__SublimeText\VS_Code_Portable_5\Code.exe'
    ''' VScode Portable: Sublime Text Style '''
    Lite            = r'G:\Data 10 - VScode\# 2026\01.VSC-4-Python-Lite\VSC-Lite-v4\Code.exe'
    ''' VScode Portable: My Lite Version (Minimal Extensions) '''
    HTML            = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__HTML\Code.exe'
    ''' VScode Portable: For HTML '''
    HTML_WebDocs    = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__HTML WebDocs\Code.exe'
    ''' VScode Portable: For My Web Docs '''
    Kodi            = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__Kodi\Code.exe'
    ''' VScode Portable: For Kodi '''
    Python          = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__Python\Code.exe'
    ''' VScode Portable: Main Python Coding '''
    Py_Flet_GUI     = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__Python Flet\Code.exe'
    ''' VScode Portable: For Flet GUI App Development '''
    Py_Plus_CoPilot = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__Python+CoPilot\Code.exe'
    ''' VScode Portable: For Use With GitHub CoPilot '''
    Yaml            = r'G:\Data 10 - VScode\# 2024\(2024)-VS-Code_4__Yaml (HomeAss)\Code.exe'
    ''' VScode Portable: For Yaml Files '''

    # VScode For My Kodi Repo 
    Kodi_Repo   = r'G:\Data 10 - VScode\_VScode_2025__4_MyRpo+Wiz\(2025)-VS-Code_4__Repo\Code.exe'
    ''' VScode Portable: For Use With My Kodi Repo '''
    # VScode For My Kodi Wizard
    Kodi_Wizard = r'G:\Data 10 - VScode\_VScode_2025__4_MyRpo+Wiz\(2025)-VS-Code_4__TSvpn-Wiz\Code.exe'
    ''' VScode Portable: For Use With My Kodi Wizard '''
    
    # Template
    # --------
    # VScode For My __Project_Name_Here__
    # VSC_Portable_Name_HERE = r'__VSC_EXE_Path_Here__'
    # ''' VScode Portable: For Use With My __Project_Name_Here__ '''
#? === End Of Class ===

# -------------------------------------------
# My Current Kodi Repo Files + Folder Paths
# -------------------------------------------
# 

def get_key_from_Dict_value(myDict:dict[str], val:str) ->str:
    """
    Find a Dict key using a **value** in a dictionary
    ---

    - By iterating over the dictionary’s key-value pairs using a for-loop
    - If the given value matches the searched Dict value, then return the corresponding key
    Help URL:
        - https://blog.finxter.com/5-best-ways-to-get-a-key-from-a-value-in-a-python-dictionary/

    Args:
        myDict (dict[str]): The Python Dict
        val (str): The Value in the dict you want to match

    Returns:
        (str): The Key for the corresponding given Value
    """
    for key, value in myDict.items():
        if value == val:
            return key
    return "Key not found"
#? === End Of Function ===


def get_VSC_list_idx(VSC_Name_Value:str) ->int:
    #? Correct List Index of all my Class vars
    VSC_idx_Dict = {
        '0': 'SubText',
        '1': 'Lite',
        '2': 'HTML',
        '3': 'HTML_WebDocs',
        '4': 'Kodi',
        '5': 'Python',
        '6': 'Py_Flet_GUI',
        '7': 'Py_Plus_CoPilot',
        '8': 'Yaml',
        '9': 'Kodi_Repo',
        '10': 'Kodi_Wizard',
    }
    # VSC_Porta = VSC_idx_Dict.get(VSC_Name)
    VSC_Porta_key_num = get_key_from_Dict_value(VSC_idx_Dict, VSC_Name_Value)
    
    return int(VSC_Porta_key_num)
#? === End Of Function ===

#todo: My Wanted Files + Folder Paths
#^ Open the Folder Path FIRST!! - Then the file paths
paths_2_files_list = [
    # NOTE:Open This Project Folder First!!
    r'\\192.168.4.212\web\HTML_Web_Docs_2025\10.Brave-Help-WDs\00--My-Brave-Start-Page-2025\v3.0',
    # Then These...
    # NOTE:Repo Project Files
    r'\\192.168.4.212\web\HTML_Web_Docs_2025\10.Brave-Help-WDs\00--My-Brave-Start-Page-2025\v3.0\Brave_USB+Streaming__Startup_Page_01.html',
    r'\\192.168.4.212\web\HTML_Web_Docs_2025\10.Brave-Help-WDs\00--My-Brave-Start-Page-2025\v3.0\Brave_USB+Streaming__Startup_Page_01--ALL-TS_vpn.html',
    # r'G:\Data 00 - 2025 (Kodi Repo +Wiz TS-vpn)\02.DS918 Wizard-2025\v1.0 - Wiz_TS-vpn\plugin.program.STV-openwiz-VPN\uservar.py',
    # NOTE:My Wizard Text Files... @DS918
    # r'File_or_Folder_Path_03',
]

if __name__ == '__main__':
    #todo: Choose Your VScode Portable
    # MY_VSCODE_PATH = Code_Paths.Lite
    # VSCODE_PORTABLE_NAME = 'Lite'
    
    Kodi_Project_Name = 'Anime Local Watchlist'
    
    #todo: === This Works!! ===
    attr_values_list, class_attrs_list = Get_My_class_Attrs.Get_My_class_values(Code_Paths)
    Get_My_class_Attrs.display_found_class_attrs(attr_values_list, class_attrs_list)
    
    #todo: Choose Your VScode Portable
    # So that I can use the Name of the VSC Portable, instead of the List index
    List_Index_num = get_VSC_list_idx('HTML_WebDocs')
    
    MY_VSCODE_PATH       = attr_values_list[List_Index_num]
    VSCODE_PORTABLE_NAME = attr_values_list[List_Index_num]  # Do Not Delete!
    
    print()
    print("=== MY_VSCODE_PATH ===")
    print(MY_VSCODE_PATH)
    print("=== MY_VSCODE_PATH ===")
    print('---')
    print(f"=== My {Kodi_Project_Name} Project: (Paths To Files + Folders) === START ")
    print('\n'.join([item for item in paths_2_files_list]))
    print(f"=== My {Kodi_Project_Name} Project: (Paths To Files + Folders) === END ")
    print()
    print()
    
    #^ === This Script MUST Be Run OUTSIDE Of VScode! === 
    # --- RUN ---
    open_files_in_vscode(MY_VSCODE_PATH, paths_2_files_list)

    print()
    print("--- ")
    print('=== Open Project Folder with VScode ===')
    print("==== Script finished successfully! ==== ")
    print("--- ")
    print()
    print()
    
    #^ NOTE: Closing the CMD window for this script will also close the VScode Portable
    #todo: Date: 29th/May/2026
    #todo: [CMD Window Complete Fix!] for ALL VSC Portables!
    #todo: FIX.. Windows-specific flag to prevent subprocess from opening a new CMD window
    #todo: And Stop CMD being linked to the opened VSC app, or other apps opened by CMD
    # CREATE_NO_WINDOW = 0x08000000
    
    #todo: [CMD Window Temp Fix] I don't know why but... (Kodi_Wizard VSC Only)
    #todo: VScode Portable launched perfectly & didn't close with the CMD window!!
    #todo: Then I comment-out the pause_cmd() function, & VScode still launched with NO Probs!
    #todo: NOTE... I ran the script by directly clicking on it
    
    #^ Leave this on if you want to see the Debug Prints, in the CMD Window
    pause_cmd()

