import sys, os
import shutil
import subprocess
from git import Repo, GitCommandError

REPO_URL = "https://github.com/rogers228/ispc_maintain.git"
TARGET_DIR = os.path.join(os.environ["USERPROFILE"], "Documents", "ispc_maintain")

def check_git_installed():
    """確認系統是否已安裝 Git"""
    git_path = shutil.which("git")
    if git_path:
        print(f"✅ 檢測到 Git：{git_path}")
        return True
    else:
        print("❌ 未偵測到 Git。")
        print("請先安裝 Git 後再執行此程式：")
        print("下載網址：https://git-scm.com/download/win")
        input("按任意鍵結束...")
        return False

def find_python_env(start_path=None, env_name="python-3.12.9"):
    # 尋找 python 執行環境
    if start_path is None:
        start_path = os.path.dirname(os.path.abspath(sys.argv[0]))
    current = start_path
    while True:
        if os.path.basename(current) == env_name:
            return current
        parent = os.path.dirname(current)
        if parent == current:
            raise FileNotFoundError(f"找不到執行環境 (資料夾名稱 {env_name})")
        current = parent

def clone_or_update_repo():
    """Clone 或更新 Repo"""
    if os.path.exists(os.path.join(TARGET_DIR, ".git")):
        print(f"📦 偵測到現有專案，正在更新...\n路徑: {TARGET_DIR}")
        try:
            repo = Repo(TARGET_DIR)
            origin = repo.remotes.origin
            origin.fetch()
            local_commit = repo.head.commit.hexsha
            remote_commit = origin.refs[repo.active_branch.name].commit.hexsha
            if local_commit == remote_commit:
                print("✅ 專案已是最新版本。")
            else:
                print("⬇️  發現新版本，執行更新中...")
                origin.pull()
                print("✅ 更新完成！")
        except GitCommandError as e:
            print("❌ 更新過程發生錯誤：", e)
    else:
        print(f"🆕 未發現專案，開始 Clone...\n目標路徑: {TARGET_DIR}")
        try:
            Repo.clone_from(REPO_URL, TARGET_DIR)
            print("✅ Clone 完成！")
        except Exception as e:
            print("❌ Clone 失敗：", e)

def create_config():
    # 建立 repository 的 config
    # 內容為該專案所使用的 python 完整路徑
    # 專案的 root 完整路徑
    content = rf"""AUTHER=Rogers
PYTHON_EXE={find_python_env()}\python.exe
ROOT={TARGET_DIR}
"""
    with open(os.path.join(TARGET_DIR, "bat", "config.txt"), 'w', encoding='utf-8') as f:
        f.write(content)

def launch_main_program():
    """啟動主程式"""
    main_bat = os.path.join(TARGET_DIR, "bat", "cmd_launch.bat")
    if os.path.exists(main_bat):
        subprocess.Popen([main_bat], shell=True, cwd=TARGET_DIR)
    else:
        print("⚠️ 找不到主程式：", main_bat)

def main():
    if not check_git_installed():
        return # 未偵測到 Git 結束
    clone_or_update_repo()
    create_config()       # 建立專案的config
    launch_main_program() # 啟動專案的啟動程序，續接

if __name__ == "__main__":
    main()


