import os
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, env=None):
    return subprocess.run(
        [sys.executable, str(SCRIPT), *args],
        capture_output=True,
        text=True,
        env=env,
    )


class FormatMdActionTests(unittest.TestCase):
    def test_format_md_invokes_prettier_from_path(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            root = Path(tmp_dir)
            (root / "README.md").write_text("# Title\n", encoding="utf-8")

            bin_dir = root / "bin"
            bin_dir.mkdir()
            prettier = bin_dir / "prettier"
            prettier.write_text(
                "#!/usr/bin/env python3\n"
                "from pathlib import Path\n"
                "Path(\".prettier_called\").write_text(\"ok\")\n",
                encoding="utf-8",
            )
            prettier.chmod(0o755)

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

[format_md]
# tool defaults to prettier
# keep default globs
"""
            config_path = root / "playbook.toml"
            config_path.write_text(config_body, encoding="utf-8")

            env = os.environ.copy()
            env["PATH"] = f"{bin_dir}:{env.get('PATH', '')}"

            result = run_cli("-config", str(config_path), env=env)
            self.assertEqual(result.returncode, 0, msg=result.stderr)
            self.assertTrue((root / ".prettier_called").exists())


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