#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""双 wheel 升级安全慢测试(SC4 唯一自动化证据链;PACK-06,tdd 慢通道)。

链路(RESEARCH「升级验证」配方逐字落地):旧轮(git worktree @ v0.1.1——setuptools-scm
需 .git,git archive 不可替代)→ 干净 venv 安装 → init 建工作区(marker 只带 schema: 1)
→ 预置 tasks/runs/pool/inventory 四类既有数据(逐字节基准)→ pip install --upgrade 新轮
(ROOT 构建)→ 断言:
1) 数据逐字节完好(inventory 另做 YAML 可解析 + servers 键断言)+ 旧 marker 经
   新轮 wsroot.marker_schema 回退读 == 1(兼容红线,安装副本实锚)
2) 升级后 plan 落工作区 runs/(rc==0)
3) site-packages/ohos_devloop 升级 + 运行后零用户数据(runs/tasks/workspace_pool.yaml)
4) 新轮 init 生成的工作区 marker 双键带 schema_version 戳

网络依赖:venv pip install 拉 PyYAML/Pillow 走 PyPI(与 test_installed_smoke 同款 A3
既有约定;离线环境本模块红——不新引入)。时长:两次构建 + venv + 升级链 ≈ 3-5 分钟。

用法:python -m unittest tests.test_upgrade_safety -v
"""
import os
import re
import subprocess
import sys
import tempfile
import unittest
import zipfile
from pathlib import Path

import yaml

ROOT = Path(__file__).resolve().parents[1]
OLD_TAG = "v0.1.1"  # 旧轮 tag:marker 只写 schema: 1 的最后版本(兼容红线的实锚)


def build_wheel(cwd: Path) -> Path:
    """在指定目录构建 wheel 到独立临时 outdir(旧轮在 worktree 内、新轮在 ROOT,不污染仓库)。"""
    out = tempfile.mkdtemp(prefix="wheelout-")
    subprocess.run([sys.executable, "-m", "build", "--wheel", "--outdir", out],
                   cwd=str(cwd), check=True, capture_output=True, timeout=600)
    return next(Path(out).glob("*.whl"))


def wheel_metadata_version(wheel: Path) -> str:
    """读 wheel dist-info/METADATA 的 Version 行(与 test_installed_smoke 同源实现,不引 packaging)。"""
    with zipfile.ZipFile(wheel) as z:
        meta = next(n for n in z.namelist() if n.endswith(".dist-info/METADATA"))
        text = z.read(meta).decode("utf-8", errors="replace")
    for line in text.splitlines():
        if line.lower().startswith("version:"):
            return line.split(":", 1)[1].strip()
    raise AssertionError(f"METADATA 缺 Version 行: {meta}")


def _ver_tuple(v: str) -> tuple[int, ...] | None:
    """'0.1.1' / '0.1.2.dev3+g<sha>' → (0,1,1)/(0,1,2);解析不出 → None(apply.py 先例)。"""
    m = re.match(r"v?(\d+(?:\.\d+)*)", str(v).strip())
    return tuple(int(x) for x in m.group(1).split(".")) if m else None


class UpgradeSafetyTest(unittest.TestCase):
    """旧轮(v0.1.1 worktree)→ venv → init → 预置数据 → 升级新轮 → SC4 四断言。"""

    @classmethod
    def setUpClass(cls):
        cls._tmp = tempfile.TemporaryDirectory(prefix="upgrade-safety-")
        cls.tmp = Path(cls._tmp.name)
        # a) 旧轮:worktree 检出 OLD_TAG(setuptools-scm 需 .git 上下文 → 版本精确 0.1.1)
        cls.wt = cls.tmp / "wt"
        subprocess.run(["git", "-C", str(ROOT), "worktree", "add", "--detach",
                        str(cls.wt), OLD_TAG], check=True, capture_output=True, timeout=300)
        cls.old_wheel = build_wheel(cls.wt)
        # b) 新轮:ROOT 构建;版本前进先决(坑位 5:HEAD 精确在 v tag 时新旧轮版本相等,
        #    --upgrade 无动作 → force-reinstall 兜底,弱化验证——仍测数据兼容,版本前进实证让位)
        cls.new_wheel = build_wheel(ROOT)
        cls.old_ver = wheel_metadata_version(cls.old_wheel)
        cls.new_ver = wheel_metadata_version(cls.new_wheel)
        cls.version_advanced = (_ver_tuple(cls.new_ver) or ()) > (_ver_tuple(cls.old_ver) or ())
        if not cls.version_advanced:
            print(f"WARN: 新轮 {cls.new_ver} 未严格前进于旧轮 {cls.old_ver}——"
                  "pip --force-reinstall 兜底(版本前进实证跳过,数据兼容断言照跑)",
                  file=sys.stderr)
        # c) venv + 装旧轮 + init 工作区(旧轮 marker 只带 schema: 1)
        cls.venv = cls.tmp / "venv"
        subprocess.run([sys.executable, "-m", "venv", str(cls.venv)],
                       check=True, capture_output=True, timeout=300)
        bindir = cls.venv / ("Scripts" if os.name == "nt" else "bin")
        exe = ".exe" if os.name == "nt" else ""
        cls.venv_py = bindir / f"python{exe}"
        cls.cli = bindir / f"ohos-devloop{exe}"
        subprocess.run([str(cls.venv_py), "-m", "pip", "install", str(cls.old_wheel),
                        "--quiet", "--disable-pip-version-check"],
                       check=True, capture_output=True, timeout=600)
        cls.ws = cls.tmp / "ws"
        cls.fake_home = cls.tmp / "fake-home"  # G-7 防污染:init 默认展开技能(新轮),统一重定向假 home
        cls.fake_home.mkdir()
        p = subprocess.run([str(cls.cli), "init", str(cls.ws)],
                           capture_output=True, text=True,
                           env={**os.environ, "USERPROFILE": str(cls.fake_home),
                                "HOME": str(cls.fake_home)},
                           encoding="utf-8", errors="replace", timeout=120)
        assert p.returncode == 0, f"旧轮 init 失败: {p.stderr}"
        # d) 预置既有数据(SC4 数据类 tasks/runs/pool/inventory 全覆盖)+ 逐字节基准
        #    (inventory.yaml 为旧轮 init 生成的占位模板产物——升级前立即 read_bytes 捕获基准)
        (cls.ws / "tasks" / "t-1").mkdir(parents=True)
        (cls.ws / "tasks" / "t-1" / "task.md").write_text(
            "# t-1\n\n- 唯一标记行: UPGRADE-SEED-task-7f3a\n", encoding="utf-8")
        (cls.ws / "runs" / "seed-run").mkdir(parents=True)
        (cls.ws / "runs" / "seed-run" / "results.json").write_text(
            '{"seed": "UPGRADE-SEED-run-91c2", "steps": []}\n', encoding="utf-8")
        (cls.ws / "workspace_pool.yaml").write_text(
            "# 池登记种子\nworkspaces:\n  - path: /ws/UPGRADE-SEED-pool-4b8d\n"
            "    task: seed-task\n    baseline: seed\n", encoding="utf-8")
        cls.baselines = {
            "tasks/t-1/task.md": (cls.ws / "tasks" / "t-1" / "task.md").read_bytes(),
            "runs/seed-run/results.json":
                (cls.ws / "runs" / "seed-run" / "results.json").read_bytes(),
            "workspace_pool.yaml": (cls.ws / "workspace_pool.yaml").read_bytes(),
            "config/inventory.yaml": (cls.ws / "config" / "inventory.yaml").read_bytes(),
        }
        # e) 升级新轮 + 版本前进实证(升级后 console version == 新轮 METADATA 版本)
        upgrade = ["install", "--force-reinstall"] if not cls.version_advanced \
            else ["install", "--upgrade"]
        subprocess.run([str(cls.venv_py), "-m", "pip"] + upgrade +
                       [str(cls.new_wheel), "--quiet", "--disable-pip-version-check"],
                       check=True, capture_output=True, timeout=600)
        v = subprocess.run([str(cls.cli), "version"], cwd=str(cls.tmp),
                           capture_output=True, text=True, timeout=120)
        assert v.returncode == 0 and v.stdout.strip() == cls.new_ver, \
            f"升级后版本异常: stdout={v.stdout!r} 期望新轮 {cls.new_ver!r} stderr={v.stderr!r}"
        # site-packages 包根(cwd 离开仓根定位,防仓内包目录遮蔽 import——02-01 Rule 1 先例)
        cls.pkg_root = Path(subprocess.run(
            [str(cls.venv_py), "-c",
             "import ohos_devloop, pathlib; print(pathlib.Path(ohos_devloop.__file__).parent)"],
            cwd=str(cls.tmp), capture_output=True, text=True, check=True,
            timeout=120).stdout.strip())

    @classmethod
    def tearDownClass(cls):
        r = subprocess.run(["git", "-C", str(ROOT), "worktree", "remove", "--force",
                            str(cls.wt)], capture_output=True, text=True, timeout=300)
        if r.returncode != 0:
            print(f"WARN: worktree 清理失败(忽略,留档): {r.stderr.strip()}", file=sys.stderr)
        try:
            cls._tmp.cleanup()
        except OSError as e:  # Windows 文件锁偶发:清理失败不阻断测试结果
            print(f"WARN: 临时目录清理失败(忽略): {e}", file=sys.stderr)

    def test_upgrade_preserves_workspace_data(self):
        """SC4:升级后 tasks/runs/pool/inventory 与预置基准逐字节相等;inventory 仍可被
        新工具解析(YAML 可解析 + servers 键);旧 marker 经新轮 marker_schema 回退读 == 1。"""
        for rel, baseline in self.baselines.items():
            with self.subTest(item=rel):
                p = self.ws / rel
                self.assertTrue(p.is_file(), f"升级后丢失: {p}")
                self.assertEqual(p.read_bytes(), baseline, f"升级后内容漂移: {p}")
        inv = yaml.safe_load((self.ws / "config" / "inventory.yaml").read_text(encoding="utf-8"))
        self.assertIn("servers", inv)  # 旧轮 init 产物升级后既字节不变、也可被新工具解析
        marker = yaml.safe_load((self.ws / "ohos-workspace.yaml").read_text(encoding="utf-8"))
        self.assertEqual(marker.get("workspace"), "ohos-devloop")  # marker 仍可解析
        # 旧 marker(只带 schema: 1)经新轮安装副本 wsroot.marker_schema 回退读 == 1(兼容红线实锚)
        code = ("import pathlib, sys, ohos_devloop;"
                "sys.path.insert(0, str(pathlib.Path(ohos_devloop.__file__).parent / 'scripts'));"
                "import wsroot; print(wsroot.marker_schema(pathlib.Path(sys.argv[1])))")
        p = subprocess.run([str(self.venv_py), "-c", code, str(self.ws)],
                           capture_output=True, text=True, timeout=120)
        self.assertEqual(p.returncode, 0, p.stderr)
        self.assertEqual(p.stdout.strip(), "1")

    def test_upgrade_plan_writes_to_workspace(self):
        """升级后从工作区跑新轮 plan → rc==0 且运行数据落 ws/runs/(plan-*.json)。"""
        p = subprocess.run([str(self.cli), "apply", "examples/smoke.yaml", "plan"],
                           cwd=str(self.ws), capture_output=True, text=True,
                           encoding="utf-8", errors="replace", timeout=300)
        self.assertEqual(p.returncode, 0, p.stderr)
        self.assertIsNotNone(next(iter((self.ws / "runs").glob("smoke-plan-*.json")), None),
                             f"plan JSON 未落工作区 runs/: {self.ws / 'runs'}")

    def test_upgrade_leaves_site_packages_clean(self):
        """SC3/SC4:升级 + 运行后 site-packages/ohos_devloop 零用户数据。"""
        p = subprocess.run([str(self.cli), "apply", "examples/smoke.yaml", "plan"],
                           cwd=str(self.ws), capture_output=True, text=True,
                           encoding="utf-8", errors="replace", timeout=300)
        self.assertEqual(p.returncode, 0, p.stderr)
        for name in ("runs", "tasks", "workspace_pool.yaml"):
            with self.subTest(item=name):
                self.assertFalse((self.pkg_root / name).exists(),
                                 f"用户数据泄漏进 site-packages: {self.pkg_root / name}")

    def test_new_init_writes_schema_version(self):
        """SC4 尾句:新轮 init 生成的工作区 marker 双键带戳(schema_version + 过渡 schema)。"""
        ws2 = self.tmp / "ws2"
        p = subprocess.run([str(self.cli), "init", str(ws2)],
                           capture_output=True, text=True,
                           env={**os.environ, "USERPROFILE": str(self.fake_home),
                                "HOME": str(self.fake_home)},  # G-7:新轮 init 展开技能 → 假 home
                           encoding="utf-8", errors="replace", timeout=120)
        self.assertEqual(p.returncode, 0, p.stderr)
        marker = yaml.safe_load((ws2 / "ohos-workspace.yaml").read_text(encoding="utf-8"))
        self.assertEqual(marker.get("schema_version"), 1)
        self.assertEqual(marker.get("schema"), 1)


if __name__ == "__main__":
    unittest.main()