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 SyncTemplatesPlaceholdersTests(unittest.TestCase):
    def test_main_language_placeholder_replaced(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            config_body = f"""
[playbook]
project_root = \"{tmp_dir}\"

[sync_rules]

[sync_standards]
langs = [\"cpp\", \"tsl\"]
"""
            config_path = Path(tmp_dir) / "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_md = Path(tmp_dir) / "AGENTS.md"
            text = agents_md.read_text(encoding="utf-8")
            self.assertIn(".agents/cpp/index.md", text)
            self.assertNotIn("{{MAIN_LANGUAGE}}", text)

            rules_md = Path(tmp_dir) / "AGENT_RULES.md"
            rules_text = rules_md.read_text(encoding="utf-8")
            self.assertIn("docs/standards/playbook/scripts/plan_progress.py", rules_text)
            self.assertNotIn("{{PLAYBOOK_SCRIPTS}}", rules_text)


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