import json
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from mixersystem.sync import PACKAGE_DIR, sync


class SyncSettingsTest(unittest.TestCase):
    def test_sync_creates_linear_block_defaults(self) -> None:
        with TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            (root / "app" / ".mix").mkdir(parents=True, exist_ok=True)
            (root / "app" / ".mix" / "doc.md").write_text("# App\n")

            sync(project_root=tmpdir)

            settings = json.loads((root / ".mixer" / "settings.json").read_text())
            self.assertIn("modules", settings)
            self.assertIn("app", settings["modules"])
            self.assertEqual(settings["linear"]["team_prefix"], "")
            self.assertEqual(settings["linear"]["team_id"], "")

    def test_sync_preserves_existing_linear_values(self) -> None:
        with TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            (root / "app" / ".mix").mkdir(parents=True, exist_ok=True)
            (root / "app" / ".mix" / "doc.md").write_text("# App\n")
            (root / ".mixer").mkdir(parents=True, exist_ok=True)

            existing = {
                "modules": {},
                "linear": {
                    "team_prefix": "ENG",
                    "team_id": "team_123",
                    "extra": "keep-me",
                },
                "custom": {"x": 1},
            }
            (root / ".mixer" / "settings.json").write_text(json.dumps(existing, indent=2) + "\n")

            sync(project_root=tmpdir)

            settings = json.loads((root / ".mixer" / "settings.json").read_text())
            self.assertEqual(settings["linear"]["team_prefix"], "ENG")
            self.assertEqual(settings["linear"]["team_id"], "team_123")
            self.assertEqual(settings["linear"]["extra"], "keep-me")
            self.assertEqual(settings["custom"]["x"], 1)
            self.assertIn("app", settings["modules"])

    def test_sync_copies_runtime_readme_from_package(self) -> None:
        with TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            (root / "app" / ".mix").mkdir(parents=True, exist_ok=True)
            (root / "app" / ".mix" / "doc.md").write_text("# App\n")

            sync(project_root=tmpdir)

            generated = (root / ".mixer" / "README.md").read_text()
            expected = (PACKAGE_DIR / "README.md").read_text()
            self.assertEqual(generated, expected)


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