import tempfile
import unittest
from pathlib import Path

import sync_version


class SyncVersionTests(unittest.TestCase):
    def create_repo(self) -> Path:
        tempdir = tempfile.TemporaryDirectory()
        self.addCleanup(tempdir.cleanup)
        root = Path(tempdir.name)
        (root / "Cargo.toml").write_text(
            '[package]\nname = "athena_rs"\nversion = "0.83.2"\n\n[dependencies]\n'
        )
        (root / "README.md").write_text("# Athena RS 0.83.2\n\nBody\n")
        (root / "openapi.yaml").write_text(
            "openapi: 3.0.3\ninfo:\n  title: Athena RS\n  version: 0.83.2\n"
        )
        return root

    def test_sync_versions_updates_all_targets(self) -> None:
        root = self.create_repo()

        updated = sync_version.sync_versions(root, "0.84.0")

        self.assertEqual(updated, ["Cargo.toml", "README.md", "openapi.yaml"])
        self.assertEqual(sync_version.collect_versions(sync_version.get_version_files(root)), {
            "Cargo.toml": "0.84.0",
            "README.md": "0.84.0",
            "openapi.yaml": "0.84.0",
        })

    def test_check_detects_drift(self) -> None:
        root = self.create_repo()
        (root / "README.md").write_text("# Athena RS 0.82.0\n\nBody\n")

        exit_code = sync_version.run_check(root, None)

        self.assertEqual(exit_code, 1)

    def test_normalize_version_accepts_prefixed_release_tag(self) -> None:
        self.assertEqual(sync_version.normalize_version("v1.2.3"), "1.2.3")


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