import importlib.util
import os
import subprocess
import tempfile
import unittest


MODULE_PATH = os.path.join(os.path.dirname(__file__), "gc-remote-merged-worktrees.py")
SPEC = importlib.util.spec_from_file_location("gc_remote_merged_worktrees", MODULE_PATH)
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)


class MergedWorktreeTest(unittest.TestCase):
    def test_plan_protects_dirty_and_selects_absorbed_clean_worktree(self):
        with tempfile.TemporaryDirectory() as root:
            main = os.path.join(root, "repo")
            worktrees = os.path.join(main, ".worktree")
            subprocess.run(["git", "init", "-b", "master", main], check=True, stdout=subprocess.DEVNULL)
            subprocess.run(["git", "-C", main, "config", "user.email", "test@example.com"], check=True)
            subprocess.run(["git", "-C", main, "config", "user.name", "Test"], check=True)
            with open(os.path.join(main, "base.txt"), "w", encoding="utf-8") as handle:
                handle.write("base\n")
            subprocess.run(["git", "-C", main, "add", "base.txt"], check=True)
            subprocess.run(["git", "-C", main, "commit", "-m", "base"], check=True, stdout=subprocess.DEVNULL)
            subprocess.run(["git", "-C", main, "remote", "add", "origin", main], check=True)
            subprocess.run(["git", "-C", main, "fetch", "origin", "master"], check=True, stdout=subprocess.DEVNULL)
            os.makedirs(worktrees)
            clean = os.path.join(worktrees, "clean")
            dirty = os.path.join(worktrees, "dirty")
            subprocess.run(["git", "-C", main, "worktree", "add", "-b", "clean-branch", clean, "master"], check=True, stdout=subprocess.DEVNULL)
            subprocess.run(["git", "-C", main, "worktree", "add", "-b", "dirty-branch", dirty, "master"], check=True, stdout=subprocess.DEVNULL)
            with open(os.path.join(dirty, "dirty.txt"), "w", encoding="utf-8") as handle:
                handle.write("dirty\n")
            config = {"providerId": "TEST", "mergedWorktrees": {"enabled": True, "mainRoot": main, "workspaceRoots": [worktrees], "baseRef": "origin/master", "minAgeHours": 0, "scanBudgetMs": 5000, "cherryCheckTimeoutSeconds": 2, "manualMaxDeletePerRun": 10}}
            plan = MODULE.merged_worktree_plan(config)
            self.assertEqual([clean], [item["path"] for item in plan["candidates"]])
            self.assertIn("dirty-worktree", [item["reason"] for item in plan["protected"]])


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