import pytest
from project_brain.build.languages.cpp import CppRule


@pytest.fixture
def rule():
    return CppRule()


def test_language_name(rule):
    assert rule.language_name == "cpp"


def test_extracts_ranged_relation_evidence_and_type_bindings(rule):
    source = b'''class User { public: int name; void save(); };
void run(User &user) {
    User alias;
    user.save();
    alias.name = 1;
}
'''
    result = rule.parse(source, "main.cpp")
    run = next(function for function in result.functions if function.name == "run")

    assert any(
        fact.kind == "call" and fact.name == "save" and fact.receiver == "user"
        and fact.byte_end > fact.byte_start
        for fact in run.references
    )
    assert any(
        fact.kind == "write" and fact.name == "name" and fact.receiver == "alias"
        for fact in run.references
    )
    assert {binding.name for binding in run.type_bindings} >= {"user", "alias"}


def test_parse_function(rule):
    source = b'int create_order(int id) { return 0; }'
    result = rule.parse(source, "main.cpp")
    assert len(result.functions) >= 1
    assert result.functions[0].name == "create_order"


def test_parse_class(rule):
    source = b'''
class OrderService {
public:
    void createOrder(int id);
private:
    void validate(int id);
};
'''
    result = rule.parse(source, "service.cpp")
    assert len(result.classes) >= 1
    assert result.classes[0].name == "OrderService"
    assert result.classes[0].kind == "class"


def test_parse_class_bases(rule):
    result = rule.parse(
        b"class Child : public Base, private ns::Mixin {};",
        "service.cpp",
    )

    assert result.classes[0].bases == ["Base", "ns::Mixin"]


def test_cpp_declaration_preserves_elaborated_struct_parameter_type(rule):
    result = rule.parse(
        b"int read_async(struct Context *ctx, const struct Handle *handle);",
        "api.hpp",
    )

    function = next(item for item in result.functions if item.name == "read_async")
    assert function.params == [
        {"name": "ctx", "type": "struct Context *ctx"},
        {"name": "handle", "type": "const struct Handle *handle"},
    ]


def test_cpp_explicit_template_calls_emit_call_evidence(rule):
    result = rule.parse(
        b"template <typename T> T identity(T value) { return value; }\n"
        b"int use(int value) { return identity<int>(value); }\n",
        "template.cpp",
    )

    function = next(item for item in result.functions if item.name == "use")
    template = next(item for item in result.functions if item.name == "identity")
    assert template.kind == "function_template"
    assert template.line_start == 1
    assert function.calls == ["identity"]
    assert [
        (fact.kind, fact.name)
        for fact in function.references
        if fact.kind == "template_call"
    ] == [("template_call", "identity")]


def test_cpp_class_template_keeps_template_kind_and_full_span(rule):
    result = rule.parse(
        b"template <typename T>\nclass Box { public: T value; };\n",
        "template.cpp",
    )

    template = next(item for item in result.classes if item.name == "Box")
    assert template.kind == "class_template"
    assert template.line_start == 1


def test_parse_struct(rule):
    source = b'struct Point { int x; int y; };'
    result = rule.parse(source, "main.cpp")
    structs = [c for c in result.classes if c.kind == "struct"]
    assert len(structs) >= 1


def test_parse_include(rule):
    source = b'#include <iostream>\n#include "service.h"'
    result = rule.parse(source, "main.cpp")
    assert len(result.imports) >= 2


def test_parse_namespace(rule):
    source = b'''
namespace orders {
    void process() {}
}
'''
    result = rule.parse(source, "main.cpp")
    fn_names = [f.name for f in result.functions]
    assert "process" in fn_names


def test_is_test_file(rule):
    assert rule.is_test_file("test_main.cpp") is True
    assert rule.is_test_file("main_test.cpp") is True
    assert rule.is_test_file("main.cpp") is False


def test_cpp_else_condition_is_negated(rule):
    source = b'''#ifdef _WIN32
void win_func() {}
#else
void posix_func() {}
#endif
'''

    result = rule.parse(source, "platform.cpp")
    conds = {function.name: function.cfg_conditions for function in result.functions}

    assert conds["win_func"] == ["_WIN32"]
    assert conds["posix_func"] == ["!_WIN32"]


def test_cpp_ignores_invalid_text_in_literal_if_zero(rule):
    source = b'''#if 0
this is deliberately not C++ !!!
#endif
int active() { return 1; }
'''

    result = rule.parse(source, "inactive.cpp")

    assert [function.name for function in result.functions] == ["active"]


def test_cpp_ignores_invalid_text_in_literal_zero_elif(rule):
    source = b'''#if 0
not valid C++ at all
#elif 0
still not valid C++
#else
int active() { return 1; }
#endif
'''

    result = rule.parse(source, "inactive_elif.cpp")

    assert [function.name for function in result.functions] == ["active"]


def test_cpp20_module_markers_do_not_reject_exported_functions(rule):
    source = b'''export module service;
export int active() { return 1; }
'''

    result = rule.parse(source, "service.cpp")

    assert [function.name for function in result.functions] == ["active"]


def test_cpp_else_preserves_boolean_expression(rule):
    source = b'''#if defined(A) || defined(B)
void enabled() {}
#else
void disabled() {}
#endif
'''

    result = rule.parse(source, "condition.cpp")
    conds = {function.name: function.cfg_conditions for function in result.functions}

    assert conds["enabled"] == ["A || B"]
    assert conds["disabled"] == ["!(A || B)"]


def test_cpp_recovers_macro_parse_errors_inside_function_bodies(rule):
    source = b'''int before() { return 1; }
int macro_user() {
    struct Item value UNUSED;
    return 2;
}
int after() { return 3; }
'''

    result = rule.parse(source, "macro.cpp")

    assert [function.name for function in result.functions] == [
        "before", "macro_user", "after",
    ]


def test_cpp_keeps_complete_symbols_around_top_level_syntax_errors(rule):
    source = b'''int intact() { return 1; }
int broken(
'''

    result = rule.parse(source, "broken.cpp")

    assert [function.name for function in result.functions] == ["intact"]


def test_cpp_extracts_pointer_and_reference_return_functions(rule):
    source = b'''Response *request_async(int id) { return nullptr; }
const Item &current_item() { static Item item; return item; }
const Item &select_item(Arg &&candidate) { return candidate.item; }
'''

    result = rule.parse(source, "returns.cpp")
    functions = {function.name: function for function in result.functions}

    assert set(functions) == {"request_async", "current_item", "select_item"}
    assert functions["request_async"].return_type == "Response *"
    assert functions["current_item"].return_type == "Item &"
    assert functions["select_item"].return_type == "Item &"


def test_cpp_collects_header_symbol_evidence(rule):
    source = b'''#ifndef MODEL_HPP
#define MODEL_HPP
#define SIZE 4
namespace api {
using UserId = long;
typedef void (*Callback)(int);
class User {
public:
    int age;
    void (*on_change)(int);
private:
    static int count;
};
enum State { Ready = 1, Done };
extern int total;
}
#endif
'''
    result = rule.parse(source, "model.hpp")
    symbols = {(symbol.kind, symbol.name): symbol for symbol in result.symbols}

    assert ("macro", "MODEL_HPP") not in symbols
    assert ("macro", "SIZE") in symbols
    assert ("namespace", "api") in symbols
    assert symbols[("type_alias", "UserId")].data_type == "long"
    assert ("typedef_function_pointer", "Callback") in symbols
    assert symbols[("field", "age")].owner_name == "User"
    assert symbols[("function_pointer_field", "on_change")].owner_name == "User"
    assert symbols[("static_field", "count")].visibility == "private"
    assert symbols[("enum_constant", "Ready")].owner_name == "State"
    assert symbols[("variable", "total")].data_type == "int"


@pytest.mark.parametrize(
    ("source", "expected"),
    [
        # Single declaration form: extern "C" prefix without braces.
        (
            b'extern "C" int api_three(int x);\nint api_four(int x);\n',
            {"api_three", "api_four"},
        ),
        # One-line block form: declarations share the extern "C" line.
        (
            b'extern "C" { int a(void); int b(void); }\nint c(void);\n',
            {"a", "b", "c"},
        ),
        # Brace on the next line.
        (
            b'extern "C"\n{\n    int d(void);\n}\nint e(void);\n',
            {"d", "e"},
        ),
        # Classic multi-line block (handled by the preprocessor masker).
        (
            b'extern "C" {\n    int f1(void);\n    int f2(void);\n}\nint f3(void);\n',
            {"f1", "f2", "f3"},
        ),
        # Classic #ifdef __cplusplus guarded form.
        (
            b'#ifdef __cplusplus\nextern "C" {\n#endif\n'
            b'int g1(void);\n#ifdef __cplusplus\n}\n#endif\nint g2(void);\n',
            {"g1", "g2"},
        ),
        # Definitions (not just declarations) inside a linkage block.
        (
            b'extern "C" int h1(int x) { return x; }\n'
            b'extern "C" { int h2(void) { return 2; } }\n',
            {"h1", "h2"},
        ),
        # Nested linkage specifications.
        (
            b'extern "C" { extern "C" { int n1(void); } }\n',
            {"n1"},
        ),
        # Linkage block inside a namespace.
        (
            b'namespace ns { extern "C" { int m1(void); } }\n',
            {"m1"},
        ),
    ],
)
def test_linkage_specification_keeps_enclosed_functions(rule, source, expected):
    result = rule.parse(source, "api.h")
    names = {function.name for function in result.functions}
    assert expected <= names


def test_linkage_specification_single_declaration_reports_source_location(rule):
    result = rule.parse(
        b'int first(void);\nextern "C" int second(int x);\n',
        "api.h",
    )

    second = next(
        function for function in result.functions if function.name == "second"
    )
    assert second.line_start == 2