import tempfile
import sys
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from scripts import playbook


class PlaybookTomlParserTests(unittest.TestCase):
    def test_minimal_parser_allows_dotted_section_name(self):
        raw = """
[a.b]
key = 1
"""
        data = playbook.loads_toml_minimal(raw)
        self.assertIn("a.b", data)
        self.assertEqual(data["a.b"]["key"], 1)

    def test_minimal_parser_rejects_multiline_string(self):
        raw = '[section]\nvalue = """line1\nline2"""\n'
        with self.assertRaises(ValueError):
            playbook.loads_toml_minimal(raw)

    def test_load_config_preserves_windows_users_path_in_basic_string(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            config_path = Path(tmp_dir) / "playbook.toml"
            config_path.write_text(
                '[playbook]\nproject_root = "C:\\Users\\demo\\workspace"\n',
                encoding="utf-8",
            )

            data = playbook.load_config(config_path)

        self.assertEqual(data["playbook"]["project_root"], r"C:\Users\demo\workspace")

    def test_load_config_preserves_windows_escape_like_segments_for_path_keys(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            config_path = Path(tmp_dir) / "playbook.toml"
            config_path.write_text(
                '[playbook]\nproject_root = "C:\\tmp\\notes"\n\n'
                '[install_skills]\nagents_home = "D:\\new\\tab"\n',
                encoding="utf-8",
            )

            data = playbook.load_config(config_path)

        self.assertEqual(data["playbook"]["project_root"], r"C:\tmp\notes")
        self.assertEqual(data["install_skills"]["agents_home"], r"D:\new\tab")

    def test_load_config_keeps_already_escaped_windows_path(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            config_path = Path(tmp_dir) / "playbook.toml"
            config_path.write_text(
                '[playbook]\nproject_root = "C:\\\\Users\\\\demo\\\\workspace"\n',
                encoding="utf-8",
            )

            data = playbook.load_config(config_path)

        self.assertEqual(data["playbook"]["project_root"], r"C:\Users\demo\workspace")


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