import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "scripts" / "playbook.py"


def run_cli(*args):
    return subprocess.run(
        [sys.executable, str(SCRIPT), *args],
        capture_output=True,
        text=True,
    )


class SyncDirectoryActionsTests(unittest.TestCase):
    def test_sync_memory_bank_adds_missing_files_without_deleting_custom(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            memory_bank = root / "memory-bank"
            memory_bank.mkdir(parents=True)
            custom = memory_bank / "custom.md"
            custom.write_text("custom", encoding="utf-8")

            config_body = f"""
[playbook]
project_root = "{tmp_dir}"

[sync_memory_bank]
project_name = "Demo"
"""
            config_path = root / "playbook.toml"
            config_path.write_text(config_body, encoding="utf-8")

            result = run_cli("-config", str(config_path))
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            self.assertTrue(custom.exists())
            self.assertTrue((memory_bank / "project-brief.md").is_file())

    def test_sync_prompts_adds_missing_files_without_deleting_custom(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            prompts = root / "docs" / "prompts"
            prompts.mkdir(parents=True)
            custom = prompts / "custom.md"
            custom.write_text("custom", encoding="utf-8")

            config_body = f"""
[playbook]
project_root = "{tmp_dir}"

[sync_prompts]
"""
            config_path = root / "playbook.toml"
            config_path.write_text(config_body, encoding="utf-8")

            result = run_cli("-config", str(config_path))
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            self.assertTrue(custom.exists())
            self.assertTrue((prompts / "system" / "agent-behavior.md").is_file())

    def test_sync_memory_bank_force_overwrites_template_files_only(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            memory_bank = root / "memory-bank"
            memory_bank.mkdir(parents=True)
            custom = memory_bank / "custom.md"
            custom.write_text("custom", encoding="utf-8")

            brief = memory_bank / "project-brief.md"
            brief.write_text("OLD", encoding="utf-8")

            config_body = f"""
[playbook]
project_root = "{tmp_dir}"

[sync_memory_bank]
project_name = "Demo"
force = true
no_backup = true
"""
            config_path = root / "playbook.toml"
            config_path.write_text(config_body, encoding="utf-8")

            result = run_cli("-config", str(config_path))
            self.assertEqual(result.returncode, 0, msg=result.stderr)

            self.assertTrue(custom.exists())
            self.assertNotIn("OLD", brief.read_text(encoding="utf-8"))
            backups = list(memory_bank.glob("project-brief.md.bak.*"))
            self.assertEqual(backups, [])


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