import os
import sys
import platform
try:
    import winshell
except:
    print(f"Message: winshell is not found.")
    winshell = None
try:
    from win32com.client import Dispatch
except:
    print(f"Message: win32 is not found.")
    Dispatch = None

tkProg_Root = os.path.dirname(os.path.abspath(__file__))
python_path = sys.executable
python_dir = os.path.dirname(python_path)
if python_dir.lower() in os.environ["PATH"].lower():
    python_path = os.path.basename(python_path)

print()
print("setup.py for tkProg:Launcher.py")

# Launcher/Launcher.pyを検索して、親ディレクトリを取得
def find_launcher_dir(root):
    for dirpath, dirnames, filenames in os.walk(root):
        if "Launcher.py" in filenames:
            tkprog_X_path = os.path.dirname(dirpath)
            last_dir = os.path.basename(tkprog_X_path)
            if last_dir.startswith("tkprog_"):
                launcher_dir = dirpath
                launcher_path = os.path.join(launcher_dir, "Launcher.py")
                return launcher_path, launcher_dir, tkprog_X_path
    return None

launcher_path, launcher_dir, tkprog_X_path = find_launcher_dir(tkProg_Root)
if tkprog_X_path is None:
    raise FileNotFoundError("Launcher.pyが見つかりません。")

# tklib_pathを作成
tklib_path = os.path.join(tkProg_Root, "tklib", "python")

print()
print(f"python_path: {python_path}")
print(f"tkProg_Root: {tkProg_Root}")
print(f"tklib_path: {tklib_path}")
print(f"tkprog_X_path: {tkprog_X_path}")

# PYTHONPATHを取得し、必要に応じて追加
pythonpath = os.environ.get("PYTHONPATH", "")
if tklib_path not in pythonpath.split(os.pathsep):
    os.environ["PYTHONPATH"] = pythonpath + os.pathsep + tklib_path

# Launcher.pyのパスを作成
launcher_path = os.path.join(tkprog_X_path, "Launcher", "Launcher.py")

print(f"launcher_path: {launcher_path}")
print(f"PYTHONPATH: {pythonpath}")

# OS判定
current_os = platform.system()
print(f"OS: {current_os}")

if ' ' in python_path: python_path = '"' + python_path + '"'
if ' ' in launcher_path: launcher_path = '"' + launcher_path + '"'

if current_os == "Windows":
    print("\nCreating Launcher.bat...")
    bat_content = f"""@echo off
set tkProg_Root={tkProg_Root}
set tkprog_X_path={tkprog_X_path}
set PYTHONPATH={os.environ["PYTHONPATH"]}
set script_path={launcher_path}
{python_path} {launcher_path} %*
"""

    for dir in [tkProg_Root, launcher_dir]:
        bat_file_path = os.path.join(dir, "Launcher.bat")
        with open(bat_file_path, "w") as bat_file:
            bat_file.write(bat_content)
        print("Generated Launcher.bat:", bat_file_path)

elif current_os in ["Darwin", "Linux"]:  # macOS または Linux
    print("\nCreating Launcher.sh...")
    sh_content = f"""#!/bin/bash
export tkProg_Root="{tkProg_Root}"
export tkprog_X_path="{tkprog_X_path}"
export PYTHONPATH="{os.environ['PYTHONPATH']}"
export script_path="{launcher_path}"
{python_path} $script_path "$@"
"""

    for dir in [tkProg_Root, launcher_dir]:
        sh_file_path = os.path.join(dir, "Launcher.sh")
        with open(sh_file_path, "w") as sh_file:
            sh_file.write(sh_content)
        os.chmod(sh_file_path, 0o755)

    print("Generated Launcher.sh:", sh_file_path)

else:
    print("\nUnkown OS:", current_os)


def set_batch_file_icon(batch_file_path, icon_file_path, shortcut_path):
    # ショートカットを作成
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortCut(shortcut_path)
    shortcut.TargetPath = batch_file_path
    shortcut.IconLocation = icon_file_path
    shortcut.save()

    print(f"[{shortcut_path}] is created as shortcut for [{batch_file_path}]")


if current_os == "Windows":
    print()
    print(f"Creating shortcut of Launcher.bat...")
    if winshell is None and Dispatch is None:
        print("winshell and pywin32 are not installed.")
        print("Install them by 'pip install winshell pywin32' to create an iconed shortcut of Launcher.bat")
    elif winshell is None:
        print("winshell is not installed.")
        print("Install them by 'pip install winshell ' to create an iconed shortcut of Launcher.bat")
    elif Dispatch is None:
        print("win32com is not installed.")
        print("Install them by 'pip install pywin32' to create an iconed shortcut of Launcher.bat")
    else:
        launcher_batch_path = os.path.join(tkProg_Root, "Launcher.bat")
        icon_path = os.path.join(tkprog_X_path, "tkProg.ico")
        shortcut_path = "Launcher.lnk"
        set_batch_file_icon(launcher_batch_path, icon_path, shortcut_path)

"""
cmd = f"{python_path} chklib.py"
print()
print(f"Running [{cmd}]...")
os.system(cmd)
"""
