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

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


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


def read_entries(path: Path) -> list[str]:
    entries = []
    for line in path.read_text(encoding="utf-8").splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        entries.append(stripped)
    return entries


class GitattributesModeTests(unittest.TestCase):
    def _run_sync(self, root: Path, mode: str) -> subprocess.CompletedProcess:
        config_body = f"""
[playbook]
project_root = \"{root}\"

[sync_standards]
langs = [\"tsl\"]
gitattr_mode = \"{mode}\"
"""
        config_path = root / "playbook.toml"
        config_path.write_text(config_body, encoding="utf-8")
        return run_cli("-config", str(config_path), cwd=root)

    def test_gitattr_mode_skip(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            sentinel = "*.keep text eol=lf\n"
            (root / ".gitattributes").write_text(sentinel, encoding="utf-8")

            result = self._run_sync(root, "skip")
            self.assertEqual(result.returncode, 0)
            self.assertEqual(
                (root / ".gitattributes").read_text(encoding="utf-8"),
                sentinel,
            )

    def test_gitattr_mode_overwrite(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            (root / ".gitattributes").write_text("bad\n", encoding="utf-8")

            result = self._run_sync(root, "overwrite")
            self.assertEqual(result.returncode, 0)
            self.assertEqual(
                (root / ".gitattributes").read_text(encoding="utf-8"),
                SOURCE_GITATTR.read_text(encoding="utf-8"),
            )

    def test_gitattr_mode_block(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            result = self._run_sync(root, "block")
            self.assertEqual(result.returncode, 0)
            content = (root / ".gitattributes").read_text(encoding="utf-8")
            self.assertIn("# BEGIN playbook .gitattributes", content)
            self.assertIn("# END playbook .gitattributes", content)

    def test_gitattr_mode_append(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            src_entries = read_entries(SOURCE_GITATTR)
            (root / ".gitattributes").write_text(
                src_entries[0] + "\n", encoding="utf-8"
            )

            result = self._run_sync(root, "append")
            self.assertEqual(result.returncode, 0)
            content = (root / ".gitattributes").read_text(encoding="utf-8")
            self.assertIn("Added from playbook .gitattributes", content)


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