"""src.languages の単体テスト（66言語定義の整合性と検出ロジック）。"""
import pathlib
import sys

ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from src.languages import (
    LANGUAGES,
    LANGUAGE_NAMES,
    get_extensions,
    get_syntax_name,
    detect_language_by_ext,
)


class TestData:
    def test_language_names_sorted_and_unique(self):
        assert LANGUAGE_NAMES == sorted(LANGUAGES.keys())
        assert len(LANGUAGE_NAMES) == len(set(LANGUAGE_NAMES))

    def test_every_language_has_extensions_and_syntax(self):
        for name, (exts, syntax) in LANGUAGES.items():
            assert exts, f"{name} に拡張子がありません"
            assert all(e.startswith(".") for e in exts), f"{name} の拡張子が . で始まっていません: {exts}"
            assert syntax, f"{name} に syntax 名がありません"

    def test_has_many_languages(self):
        # 大幅拡充後（レガシー基幹系＋新興＋ドメイン言語）の下限
        assert len(LANGUAGE_NAMES) >= 110

    def test_includes_legacy_enterprise_languages(self):
        # 移行ツールとして重要なレガシー/基幹系を網羅している
        for name in ["RPG (IBM)", "REXX", "PL/I", "MUMPS (M)", "Progress 4GL / ABL",
                     "PowerBuilder", "Visual FoxPro", "ColdFusion (CFML)", "Eiffel"]:
            assert name in LANGUAGES, f"{name} が一覧に含まれていません"

    def test_includes_modern_languages(self):
        for name in ["GDScript", "Haxe", "Raku", "ReScript", "Mojo", "Carbon",
                     "Gleam", "Q#", "Cython", "Vala"]:
            assert name in LANGUAGES, f"{name} が一覧に含まれていません"


class TestGetExtensions:
    def test_known(self):
        assert get_extensions("Python") == [".py", ".pyw"]
        assert ".rs" in get_extensions("Rust")

    def test_unknown_returns_empty(self):
        assert get_extensions("Nonexistent") == []


class TestGetSyntaxName:
    def test_known(self):
        assert get_syntax_name("C++") == "C++"

    def test_unknown_returns_input(self):
        assert get_syntax_name("Foolang") == "Foolang"


class TestDetectByExt:
    def test_python(self):
        assert detect_language_by_ext("a/b/script.py") == "Python"

    def test_case_insensitive(self):
        assert detect_language_by_ext("MAIN.PY") == "Python"

    def test_rust(self):
        assert detect_language_by_ext("lib.rs") == "Rust"

    def test_no_extension_returns_none(self):
        assert detect_language_by_ext("Makefile") is None

    def test_unknown_extension_returns_none(self):
        assert detect_language_by_ext("data.unknownext") is None

    def test_ambiguous_extension_resolves_to_some_language(self):
        # .sql は複数言語が共有する。いずれかの言語に解決されればよい
        assert detect_language_by_ext("q.sql") in {"PL/SQL", "SQL", "T-SQL"}
