"""src.ecosystem の単体テスト（エコシステム対応付けと優先度ロジック）。"""
import pathlib
import sys

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

from src.ecosystem import (
    ECOSYSTEM_MAP,
    get_lang_group,
    get_ecosystem_mappings,
    classify_priority,
    sort_files_by_priority,
    get_priority_files,
    PRIORITY_PATTERNS,
)


class TestLangGroup:
    def test_known_groups(self):
        assert get_lang_group("JavaScript") == "node"
        assert get_lang_group("TypeScript") == "node"
        assert get_lang_group("Java") == "jvm"
        assert get_lang_group("Kotlin") == "jvm"

    def test_unknown_falls_back_to_lowercased_name(self):
        assert get_lang_group("Haskell") == "haskell"


class TestEcosystemMappings:
    def test_python_to_node(self):
        m = get_ecosystem_mappings("Python", "JavaScript")
        assert m.get("requirements.txt") == "package.json"
        assert m.get("Dockerfile") == "Dockerfile"

    def test_node_to_python(self):
        m = get_ecosystem_mappings("TypeScript", "Python")
        assert m.get("package.json") == "requirements.txt"

    def test_unknown_pair_returns_empty(self):
        assert get_ecosystem_mappings("Haskell", "Prolog") == {}

    def test_all_mapping_values_are_nonempty_strings(self):
        for mapping in ECOSYSTEM_MAP.values():
            for src, tgt in mapping.items():
                assert src and isinstance(src, str)
                assert tgt and isinstance(tgt, str)


class TestPriority:
    def test_type_and_config_files_are_high_priority(self):
        assert classify_priority("src/types.ts") < 1000
        assert classify_priority("config.py") < 1000
        assert classify_priority("constants.go") < 1000

    def test_regular_file_is_lowest_priority(self):
        assert classify_priority("src/handler.py") == 1000

    def test_priority_pattern_order_is_reflected(self):
        # "types" は "utils" より高優先（小さいスコア）
        assert classify_priority("types.py") < classify_priority("utils.py")

    def test_sort_puts_priority_files_first_and_is_stable(self):
        files = ["a_handler.py", "types.py", "b_handler.py", "config.py"]
        ordered = sort_files_by_priority(files)
        assert ordered[0] in {"types.py", "config.py"}
        # 同点(1000)のハンドラ群は入力順を保持（安定ソート）
        assert ordered.index("a_handler.py") < ordered.index("b_handler.py")

    def test_get_priority_files_caps_and_excludes_non_priority(self):
        files = ["types.py", "config.py", "models.py", "utils.py",
                 "helpers.py", "base.py", "handler.py", "view.py"]
        top = get_priority_files(files, max_context_files=3)
        assert len(top) == 3
        assert "handler.py" not in top  # 非優先は含めない
        assert "view.py" not in top

    def test_get_priority_files_empty_when_none_match(self):
        assert get_priority_files(["a.py", "b.py"]) == []

    def test_priority_patterns_nonempty(self):
        assert len(PRIORITY_PATTERNS) > 0
