import pytest
from pathlib import Path

from project_brain.mcp.server import ProjectBrainServer

REPOS = Path(r"C:\Users\silin\Desktop\code-momory-for-ohos\repos")


@pytest.fixture(scope="session")
def server():
    if not (REPOS / ".botbrain" / "graph" / "nodes.json").exists():
        pytest.skip("real graph not built at repos/.botbrain")
    s = ProjectBrainServer(str(REPOS))
    s._ensure_initialized()
    return s


@pytest.fixture(scope="session")
def qe(server):
    return server._query_engine


@pytest.fixture(scope="session")
def store(server):
    return server._store


def _fn_id(qe, name):
    ids = qe.symbol_index.lookup(name)
    return ids[0] if ids else None


# ---------- keyword_search (#7 file 回填, #9 测试过滤) ----------

def test_keyword_search_backfills_file(qe):
    results = qe.keyword_search("OsalMemFree")
    assert results, "expected hits for OsalMemFree"
    assert results[0]["file"] is not None, "#7 file should be backfilled"
    assert "file" in results[0]


def test_keyword_search_test_filter_modes(qe, store):
    # Use a broad query that hits both normal and test functions.
    normal = qe.keyword_search("test", top_k=50, test_filter="normal")
    tests = qe.keyword_search("test", top_k=50, test_filter="test")
    all_r = qe.keyword_search("test", top_k=50, test_filter="all")
    has_test_fns = any(n.get("is_test") for n in store.get_nodes_by_type("function"))
    if has_test_fns:
        # normal must not contain test functions; test must not contain normal.
        normal_ids = {r["id"] for r in normal}
        test_ids = {r["id"] for r in tests}
        all_ids = {r["id"] for r in all_r}
        for nid in normal_ids:
            node = store.get_node(nid)
            assert not node.get("is_test"), "normal mode leaked a test function"
        for tid in test_ids:
            node = store.get_node(tid)
            assert node.get("is_test"), "test mode leaked a non-test function"
        assert len(all_r) >= len(normal)
    else:
        assert len(tests) == 0


# ---------- locate_symbol (#17 大小写, #8 歧义) ----------

def test_locate_symbol_case_insensitive(qe):
    assert qe.locate_symbol("osalmemfree"), "#17 should match case-insensitively"


def test_locate_symbol_returns_file_path(qe, store):
    results = qe.locate_symbol("OsalMemFree")
    assert results
    assert results[0]["file"] is not None


# ---------- get_symbol_info (#8 歧义候选) ----------

def test_get_symbol_info_by_name(qe):
    info = qe.get_symbol_info("OsalMemFree")
    assert info is not None
    # OsalMemFree has multiple impls (linux/liteos/liteos_m/posix) — ambiguity is valid
    if info.get("ambiguous"):
        assert len(info["candidates"]) > 1


def test_get_symbol_info_ambiguous_init(qe):
    info = qe.get_symbol_info("__init__")
    assert info is not None
    assert info.get("ambiguous") is True, "#8 __init__ has many definitions"
    assert len(info["candidates"]) > 1


# ---------- get_callers (#1 不串配) ----------

def test_get_callers_popular_function(qe):
    callers = qe.get_callers("OsalMemFree", depth=1)
    assert len(callers) > 10, "OsalMemFree should have many callers"
    names = [c["name"] for c in callers]
    assert "OsalMemFree" not in names, "should not be its own caller"


def test_get_callers_depth_traversal(qe):
    d1 = qe.get_callers("OsalMemFree", depth=1)
    d2 = qe.get_callers("OsalMemFree", depth=2)
    assert len(d2) >= len(d1)


# ---------- get_callees (#22) ----------

def test_get_callees_returns_list(qe, store):
    fn = _fn_id(qe, "OsalMemFree")
    callees = qe.get_callees(fn, depth=1)
    assert isinstance(callees, list)


# ---------- get_dependencies (#13) ----------

def test_get_dependencies_returns_result(qe):
    deps = qe.get_dependencies("hal")
    assert "upstream" in deps and "downstream" in deps


def test_get_dependencies_nonempty(qe, store):
    modules = store.get_nodes_by_type("module")
    found_any = False
    for m in modules[:20]:
        deps = qe.get_dependencies(m["id"])
        if deps["upstream"] or deps["downstream"]:
            found_any = True
            break
    assert found_any, "#13 DEPEND edges appear to be missing entirely"


# ---------- get_module_contents (#6 去重) ----------

def test_get_module_contents_no_dup(qe, store):
    modules = store.get_nodes_by_type("module")
    target = None
    for m in modules:
        c = qe.get_module_contents(m["id"])
        if c and (c["functions"] or c["classes"]):
            target = c
            break
    assert target, "no module with contents found"
    fn_ids = [f["id"] for f in target["functions"]]
    assert len(fn_ids) == len(set(fn_ids)), "#6 duplicate functions in module"


# ---------- get_file_symbols (#11 路径归一化) ----------

def test_get_file_symbols_path_normalization(qe, store):
    files = store.get_nodes_by_type("file")
    f = files[0]
    path = f["path"]
    forward = qe.get_file_symbols(path)
    backward = qe.get_file_symbols(path.replace("/", "\\"))
    assert forward == backward, "#11 path separator should be normalized"


# ---------- get_related_tests (#5) ----------

def test_get_related_tests_returns_list(qe):
    tests = qe.get_related_tests("OsalMemFree")
    assert isinstance(tests, list)


# ---------- get_history (#15) ----------

def test_get_history_non_git(qe, store):
    history = qe.get_history("OsalMemFree")
    assert isinstance(history, list)
    has_commits = bool(store.get_nodes_by_type("commit"))
    if not has_commits:
        assert history == [], "#15 non-git project should return empty history"


# ---------- get_owner (#15) ----------

def test_get_owner_non_git(qe, store):
    owners = qe.get_owner("OsalMemFree")
    assert isinstance(owners, list)


# ---------- get_conventions (#21) ----------

def test_get_conventions_returns_list(qe):
    conventions = qe.get_conventions()
    assert isinstance(conventions, list)
    assert len(conventions) >= 1


def test_get_conventions_categories(qe):
    conventions = qe.get_conventions()
    categories = {c["category"] for c in conventions}
    assert "naming" in categories


# ---------- get_doc_links ----------

def test_get_doc_links_for_symbol(qe, store):
    targets = [e.target for e in store.edges if e.type == "DESCRIBE"]
    if not targets:
        pytest.skip("no DESCRIBE edges in graph")
    docs = qe.get_doc_links(targets[0])
    assert isinstance(docs, list)
    assert len(docs) >= 1


# ---------- impact_analysis (#4 struct 聚合) ----------

def test_impact_analysis_for_class(qe, store):
    classes = [c for c in store.get_nodes_by_type("class") if c.get("methods")]
    if not classes:
        pytest.skip("no class with methods in graph")
    cls = classes[0]
    result = qe.impact_analysis(cls["id"])
    assert result["target"] == cls["id"]
    assert "risk_level" in result


def test_impact_analysis_for_function(qe):
    result = qe.impact_analysis("OsalMemFree")
    assert "affected_functions" in result
    assert "risk_level" in result


# ---------- 重复节点检查 (#6) ----------

def test_no_duplicate_function_ids_in_file(qe, store):
    from collections import Counter
    files = store.get_nodes_by_type("file")
    f = files[0]
    symbols = qe.get_file_symbols(f["path"])
    ids = [s["id"] for s in symbols]
    assert len(ids) == len(set(ids)), "#6 duplicate symbol ids in file"


def test_graph_integrity_no_dangling_edges(store):
    node_ids = set(store.nodes.keys())
    missing = set()
    for e in store.edges:
        if e.target not in node_ids:
            missing.add((e.type, e.target))
        if e.source not in node_ids:
            missing.add((e.type, e.source))
    assert not missing, f"{len(missing)} dangling edge endpoints: {list(missing)[:5]}"