from __future__ import annotations
from dataclasses import dataclass
from typing import Any


@dataclass
class TestRecommendation:
    modified_files: list[str]
    recommended_tests: list[dict]
    direct_tests: list[dict]
    indirect_tests: list[dict]


class ReasoningEngine:
    """Higher-level reasoning built on top of QueryEngine.

    Currently only ``test_recommendation`` is used (by the MCP
    ``test_recommendation`` tool). ``impact_analysis`` lives on
    ``QueryEngine`` directly (different risk-scoring algorithm).
    """

    def __init__(self, store: Any, query_engine: Any):
        self.store = store
        self.query = query_engine

    def test_recommendation(self, modified_files: list[str]) -> TestRecommendation:
        """Recommend tests to run based on modified files."""
        direct_tests = []
        indirect_tests = []
        seen_test_ids = set()

        for file_path in modified_files:
            # Get symbols in modified files
            symbols = self.query.get_file_symbols(file_path)

            for symbol in symbols:
                symbol_id = symbol["id"]

                # Direct tests: tests that directly test this symbol
                tests = self.query.get_related_tests(symbol_id)
                for test in tests:
                    if test["id"] not in seen_test_ids:
                        seen_test_ids.add(test["id"])
                        direct_tests.append({
                            **test,
                            "reason": f"Directly tests {symbol['name']}",
                        })

                # Indirect tests: tests for callers of this symbol
                callers = self.query.get_callers(symbol_id, depth=2)
                for caller in callers:
                    caller_tests = self.query.get_related_tests(caller["id"])
                    for test in caller_tests:
                        if test["id"] not in seen_test_ids:
                            seen_test_ids.add(test["id"])
                            indirect_tests.append({
                                **test,
                                "reason": f"Tests caller {caller['name']} of {symbol['name']}",
                            })

        recommended = direct_tests + indirect_tests

        return TestRecommendation(
            modified_files=modified_files,
            recommended_tests=recommended,
            direct_tests=direct_tests,
            indirect_tests=indirect_tests,
        )