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 NoBackupFlagsTests(unittest.TestCase):
    def test_sync_rules_no_backup_skips_backup_file(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            rules = root / "AGENT_RULES.md"
            rules.write_text("old rules", encoding="utf-8")

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

[sync_rules]
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)

            backups = list(root.glob("AGENT_RULES.md.bak.*"))
            self.assertEqual(backups, [])
            self.assertTrue(rules.is_file())

    def test_sync_standards_no_backup_skips_agents_and_gitattributes_backup(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            agents = root / ".agents" / "tsl"
            agents.mkdir(parents=True)
            (agents / "index.md").write_text("old", encoding="utf-8")

            gitattributes = root / ".gitattributes"
            gitattributes.write_text("*.txt text\n", encoding="utf-8")

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

[sync_standards]
langs = ["tsl"]
gitattr_mode = "append"
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)

            agents_backups = list((root / ".agents").glob("tsl.bak.*"))
            self.assertEqual(agents_backups, [])
            git_backups = list(root.glob(".gitattributes.bak.*"))
            self.assertEqual(git_backups, [])


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