"""Tests for deterministic language detection."""

import sys
import tempfile
import unittest
from pathlib import Path

SCRIPTS = Path(__file__).parents[1] / "scripts"
sys.path.insert(0, str(SCRIPTS))

from language_detector import detect_language, platform_languages


TS_PATCH = (
    "diff --git a/src/app.ts b/src/app.ts\n"
    "--- a/src/app.ts\n+++ b/src/app.ts\n"
    "diff --git a/src/util.ts b/src/util.ts\n"
    "--- a/src/util.ts\n+++ b/src/util.ts\n"
)


class PlatformLanguageTest(unittest.TestCase):
    """Verify the mapping onto the platform's language whitelist."""

    def test_known_profile_maps_to_canonical_spelling(self):
        self.assertEqual(["Go"], platform_languages("go", ""))
        self.assertEqual(["Python"], platform_languages("python", ""))
        self.assertEqual(["Java"], platform_languages("java", ""))

    def test_universal_is_resolved_from_patch_extensions(self):
        """``universal`` is not a legal platform value, so the patch decides."""
        self.assertEqual(["TypeScript"], platform_languages("universal", TS_PATCH))

    def test_minor_language_share_is_dropped(self):
        patch = TS_PATCH * 4 + "--- a/assets/x.lua\n+++ b/assets/x.lua\n"
        self.assertEqual(["TypeScript"], platform_languages("universal", patch))

    def test_unmappable_patch_raises(self):
        with self.assertRaises(ValueError):
            platform_languages("universal", "--- a/README.md\n+++ b/README.md\n")


class LanguageDetectorTest(unittest.TestCase):
    """Verify language routing and ambiguity fallback."""

    def test_detects_go_marker(self):
        """A Go module routes to Go."""
        with tempfile.TemporaryDirectory() as directory:
            repo = Path(directory)
            (repo / "go.mod").write_text("module example\n", encoding="utf-8")
            self.assertEqual("go", detect_language(repo)["language"])

    def test_tie_falls_back_to_universal(self):
        """Equal language evidence uses universal."""
        with tempfile.TemporaryDirectory() as directory:
            repo = Path(directory)
            (repo / "a.go").write_text("", encoding="utf-8")
            (repo / "a.py").write_text("", encoding="utf-8")
            self.assertEqual("universal", detect_language(repo)["language"])


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