"""
将 dev 分支同步到 test 和 master。
使用 git reset --hard 强制对齐，绕过文件锁问题。
"""
import subprocess
import sys
import time


def run(cmd: str, retries: int = 3, delay: float = 2.0) -> bool:
    """执行 git 命令，失败时重试。"""
    for attempt in range(1, retries + 1):
        print(f"  [{attempt}/{retries}] {cmd}")
        result = subprocess.run(
            cmd, shell=True, capture_output=True, text=True,
            cwd=r"C:\NeoZQYY", encoding="utf-8", errors="replace",
        )
        if result.returncode == 0:
            if result.stdout.strip():
                print(f"    {result.stdout.strip()}")
            return True
        print(f"    失败: {result.stderr.strip()[:300]}")
        if attempt < retries:
            print(f"    等待 {delay}s 后重试…")
            time.sleep(delay)
    return False


def sync_branch(target: str, source_hash: str) -> bool:
    """将 target 分支强制对齐到 source_hash。"""
    print(f"\n{'='*50}")
    print(f"同步 {target} → {source_hash[:8]}")
    print(f"{'='*50}")

    if not run(f"git checkout --force {target}"):
        print(f"  ✗ 切换到 {target} 失败")
        return False

    # 用 reset --hard 强制对齐，不受文件锁影响
    if not run(f"git reset --hard {source_hash}"):
        print(f"  ✗ reset --hard 失败")
        return False

    print(f"  ✓ {target} 已对齐到 {source_hash[:8]}")
    return True


def main():
    # 获取 dev 的 HEAD commit
    result = subprocess.run(
        "git rev-parse dev", shell=True, capture_output=True, text=True,
        cwd=r"C:\NeoZQYY", encoding="utf-8",
    )
    if result.returncode != 0:
        print("无法获取 dev 的 HEAD，退出")
        sys.exit(1)

    dev_hash = result.stdout.strip()
    print(f"dev HEAD: {dev_hash[:8]}")

    ok = True
    for branch in ["test", "master"]:
        if not sync_branch(branch, dev_hash):
            ok = False
            print(f"  ✗ {branch} 同步失败")

    # 切回 dev
    print(f"\n切回 dev…")
    run("git checkout --force dev")

    # 恢复 stash（如果有）
    stash_result = subprocess.run(
        "git stash list", shell=True, capture_output=True, text=True,
        cwd=r"C:\NeoZQYY", encoding="utf-8",
    )
    if stash_result.stdout.strip():
        print("恢复 stash…")
        run("git stash pop")

    if ok:
        print("\n✓ 全部完成。三个分支已对齐。")
    else:
        print("\n✗ 部分分支同步失败，请检查。")
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
