"""安装逻辑 - 将 VS Code 扩展安装到目标项目"""
import os
import sys
import shutil
import subprocess
import zipfile

EXT_ID = "local.fix-bugs-terminal"
EXT_DIR = os.path.join(".vscode", "fix-bugs-ext")
VSIX_PATH = os.path.join(".vscode", "fix-bugs-terminal.vsix")


def _get_vscode_ext_dir():
    """用 importlib.resources 定位包内 vscode_ext 资源目录"""
    try:
        # Python 3.9+
        from importlib.resources import files
        return str(files("claude_fix_bugs") / "vscode_ext")
    except (ImportError, TypeError):
        # Python 3.8 fallback
        import importlib.resources as pkg_resources
        import claude_fix_bugs.vscode_ext as _pkg
        return str(pkg_resources.path(_pkg, "package.json").__enter__().parent)


def ensure_installed():
    """检查扩展是否已安装，没装则自动安装"""
    if is_ext_installed():
        return
    if not os.path.exists(EXT_DIR):
        _copy_ext_files()
    print("首次运行，安装 VS Code 扩展...")
    build_vsix(EXT_DIR, VSIX_PATH)
    install_ext(VSIX_PATH)
    print("\n扩展已安装，请重新加载 VS Code 窗口:")
    print("  Ctrl+Shift+P -> Developer: Reload Window")
    print("\n重新加载后再次运行此脚本即可。")
    sys.exit(0)


def _copy_ext_files(target_dir=None):
    """从包内复制扩展文件到项目 .vscode/fix-bugs-ext/"""
    target = target_dir or os.getcwd()
    src = _get_vscode_ext_dir()
    dest = os.path.join(target, ".vscode", "fix-bugs-ext")
    os.makedirs(dest, exist_ok=True)
    for fname in ["package.json", "extension.js"]:
        shutil.copy2(os.path.join(src, fname), dest)
    print(f"扩展文件已复制到 {dest}")
    return dest


def install(target_dir=None):
    """显式安装命令 - 复制扩展文件 + 构建 VSIX + 安装 + 更新 .gitignore"""
    target = target_dir or os.getcwd()
    dest_ext = _copy_ext_files(target)
    vsix_path = os.path.join(target, ".vscode", "fix-bugs-terminal.vsix")
    build_vsix(dest_ext, vsix_path)
    install_ext(vsix_path)
    update_gitignore(target)
    print("\n安装完成。如果是首次安装，请重新加载 VS Code 窗口:")
    print("  Ctrl+Shift+P -> Developer: Reload Window")


def build_vsix(ext_dir, vsix_path):
    with zipfile.ZipFile(vsix_path, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.writestr("[Content_Types].xml",
            '<?xml version="1.0" encoding="utf-8"?>\n'
            '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n'
            '  <Default Extension=".json" ContentType="application/json"/>\n'
            '  <Default Extension=".js" ContentType="application/javascript"/>\n'
            '  <Default Extension=".vsixmanifest" ContentType="text/xml"/>\n'
            '</Types>')
        zf.writestr("extension.vsixmanifest",
            '<?xml version="1.0" encoding="utf-8"?>\n'
            '<PackageManifest Version="2.0.0"'
            ' xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011">\n'
            '  <Metadata>\n'
            '    <Identity Language="en-US" Id="fix-bugs-terminal"'
            ' Version="1.0.0" Publisher="local"/>\n'
            '    <DisplayName>Fix Bugs Terminal</DisplayName>\n'
            '    <Description xml:space="preserve">'
            'Fix bugs in VS Code terminals</Description>\n'
            '  </Metadata>\n'
            '  <Installation>\n'
            '    <InstallationTarget Id="Microsoft.VisualStudio.Code"/>\n'
            '  </Installation>\n'
            '  <Dependencies/>\n'
            '  <Assets>\n'
            '    <Asset Type="Microsoft.VisualStudio.Code.Manifest"'
            ' Path="extension/package.json" Addressable="true"/>\n'
            '  </Assets>\n'
            '</PackageManifest>')
        for fname in ["package.json", "extension.js"]:
            fpath = os.path.join(ext_dir, fname)
            with open(fpath, "r", encoding="utf-8") as f:
                zf.writestr(f"extension/{fname}", f.read())
    print(f"VSIX 已打包: {vsix_path}")


def install_ext(vsix_path):
    vsix_abs = os.path.abspath(vsix_path)
    result = subprocess.run(
        ["code", "--install-extension", vsix_abs, "--force"],
        shell=True, capture_output=True, text=True,
    )
    if result.returncode != 0:
        print(f"警告: 扩展安装失败（code 命令返回 {result.returncode}）")
        print("请确认 VS Code 的 code 命令在 PATH 中，或手动安装:")
        print(f'  code --install-extension "{vsix_abs}" --force')
    else:
        print("扩展已安装")


def is_ext_installed():
    try:
        result = subprocess.run(
            ["code", "--list-extensions"],
            capture_output=True, text=True, shell=True,
        )
        return EXT_ID in result.stdout
    except FileNotFoundError:
        print("警告: 未找到 code 命令，请确认 VS Code 已安装且 code 在 PATH 中")
        return False


def update_gitignore(target):
    gitignore = os.path.join(target, ".gitignore")
    entries = ["_fix_trigger.json", "_fix_tmp/", "*.vsix"]
    existing = ""
    if os.path.exists(gitignore):
        with open(gitignore, "r", encoding="utf-8") as f:
            existing = f.read()
    to_add = [e for e in entries if e not in existing]
    if to_add:
        with open(gitignore, "a", encoding="utf-8") as f:
            if existing and not existing.endswith("\n"):
                f.write("\n")
            f.write("# fix-bugs tooling\n")
            for e in to_add:
                f.write(e + "\n")
        print(f".gitignore 已更新: {', '.join(to_add)}")
