"""
一次性脚本：将 Windows 系统级默认 shell 切换为 PowerShell 7
1. Windows Terminal 默认 profile → pwsh.exe
2. OpenSSH DefaultShell 注册表 → pwsh.exe
3. 系统 ComSpec 环境变量不动（保持 cmd.exe 兼容）
"""
import json
import os
import subprocess
import winreg

PWSH7 = r"C:\Program Files\PowerShell\7\pwsh.exe"

# ── 1. Windows Terminal settings.json ──
wt_settings = os.path.join(
    os.environ["LOCALAPPDATA"],
    "Packages",
    "Microsoft.WindowsTerminal_8wekyb3d8bbwe",
    "LocalState",
    "settings.json",
)
wt_preview = os.path.join(
    os.environ["LOCALAPPDATA"],
    "Packages",
    "Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe",
    "LocalState",
    "settings.json",
)

# Windows Terminal 的 PowerShell 7 profile GUID（官方固定值）
PWSH7_GUID = "{574e775e-4f2a-5b96-ac1e-a2962a402336}"

for path in [wt_settings, wt_preview]:
    if os.path.isfile(path):
        with open(path, "r", encoding="utf-8") as f:
            content = f.read()
        # 去掉 JSON 注释行（Windows Terminal 允许 // 注释）
        lines = []
        for line in content.splitlines():
            stripped = line.lstrip()
            if stripped.startswith("//"):
                continue
            lines.append(line)
        clean = "\n".join(lines)
        try:
            cfg = json.loads(clean)
        except json.JSONDecodeError:
            print(f"跳过（JSON 解析失败）: {path}")
            continue
        cfg["defaultProfile"] = PWSH7_GUID
        with open(path, "w", encoding="utf-8") as f:
            json.dump(cfg, f, indent=4, ensure_ascii=False)
        print(f"已更新 Windows Terminal defaultProfile: {path}")
    else:
        print(f"未找到 Windows Terminal 配置: {path}")

# ── 2. OpenSSH DefaultShell 注册表 ──
try:
    key = winreg.CreateKeyEx(
        winreg.HKEY_LOCAL_MACHINE,
        r"SOFTWARE\OpenSSH",
        0,
        winreg.KEY_SET_VALUE,
    )
    winreg.SetValueEx(key, "DefaultShell", 0, winreg.REG_SZ, PWSH7)
    winreg.CloseKey(key)
    print(f"已设置 OpenSSH DefaultShell → {PWSH7}")
except PermissionError:
    print("OpenSSH 注册表写入需要管理员权限，跳过（可手动以管理员运行）")
except Exception as e:
    print(f"OpenSSH 注册表写入失败: {e}")

# ── 3. 将 pwsh.exe 所在目录加到 PATH 最前面（如果不在的话）──
pwsh_dir = os.path.dirname(PWSH7)
current_path = os.environ.get("PATH", "")
if pwsh_dir.lower() not in current_path.lower():
    # 写入用户级 PATH
    try:
        key = winreg.OpenKeyEx(
            winreg.HKEY_CURRENT_USER,
            r"Environment",
            0,
            winreg.KEY_READ | winreg.KEY_SET_VALUE,
        )
        user_path, _ = winreg.QueryValueEx(key, "Path")
        if pwsh_dir.lower() not in user_path.lower():
            new_path = pwsh_dir + ";" + user_path
            winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
            print(f"已将 {pwsh_dir} 添加到用户 PATH 最前面")
        else:
            print(f"{pwsh_dir} 已在用户 PATH 中")
        winreg.CloseKey(key)
    except Exception as e:
        print(f"PATH 更新失败: {e}")
else:
    print(f"{pwsh_dir} 已在 PATH 中")

print("\n完成。新开的终端窗口将默认使用 PowerShell 7。")
