import pytest

from project_brain.build.languages.rust import RustRule


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


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


def test_file_extensions(rule):
    assert ".rs" in rule.file_extensions


def test_is_test_file(rule):
    assert rule.is_test_file("tests/integration.rs") is True
    assert rule.is_test_file("src/main.rs") is False
    assert rule.is_test_file("test.rs") is True
    assert rule.is_test_file("src/lib_test.rs") is True
    # Cargo test/benchmark directories are test contexts, not public API.
    assert rule.is_test_file("benches/perf.rs") is True


def test_extracts_ranged_relation_evidence_and_type_bindings(rule):
    source = b'''struct User { name: String }
impl User { fn save(&self) {} }
fn run(user: User) {
    user.save();
    let alias: User = user;
    alias.name = String::new();
}
'''
    result = rule.parse(source, "lib.rs")
    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, binding.type_name) for binding in run.type_bindings} >= {
        ("user", "User"), ("alias", "User"),
    }


def test_extracts_extern_c_function_declarations(rule):
    source = b'''extern "C" {
    pub fn ffrt_submit_coroutine(task: *mut core::ffi::c_void) -> i32;
    fn variadic(format: *const u8, ...) -> i32;
}
'''
    result = rule.parse(source, "ffi.rs")
    functions = {function.name: function for function in result.functions}

    assert set(functions) == {"ffrt_submit_coroutine", "variadic"}
    assert functions["ffrt_submit_coroutine"].is_definition is False
    assert functions["ffrt_submit_coroutine"].is_exported is True
    assert functions["ffrt_submit_coroutine"].line_start == 2
    assert functions["ffrt_submit_coroutine"].return_type == "i32"
    assert functions["ffrt_submit_coroutine"].linkage == "C"
    assert functions["variadic"].params[-1] == {"name": "...", "type": None}


def test_recovers_pub_use_from_macro_token_tree(rule):
    source = b'''cfg_not_ffrt! {
    pub use linux::*;
    pub use api::Thing as Alias;
}
'''
    result = rule.parse(source, "lib.rs")

    assert [(item.module, item.symbols, item.line) for item in result.imports] == [
        ("linux", ["*"], 2),
        ("api", ["Thing as Alias"], 3),
    ]
    assert all("macro:cfg_not_ffrt" in item.cfg_conditions for item in result.imports)
    assert result.reexported_names == ["*", "Alias"]
    assert rule.is_test_file("examples/demo.rs") is True


def test_parse_function(rule):
    source = b'fn hello(name: &str) -> String { format!("Hello {}", name) }'
    result = rule.parse(source, "main.rs")
    assert len(result.functions) >= 1
    fn = result.functions[0]
    assert fn.name == "hello"


def test_parse_function_params(rule):
    source = b'fn add(a: i32, b: i32) -> i32 { a + b }'
    result = rule.parse(source, "main.rs")
    fn = result.functions[0]
    assert fn.name == "add"
    param_names = [p["name"] for p in fn.params]
    assert "a" in param_names
    assert "b" in param_names


def test_parse_async_function(rule):
    source = b'async fn fetch_data(url: &str) -> Result<String, Error> { Ok("data".to_string()) }'
    result = rule.parse(source, "main.rs")
    fn = result.functions[0]
    assert fn.name == "fetch_data"
    assert fn.is_async is True


def test_parse_struct(rule):
    source = b'''
struct OrderService {
    name: String,
}
'''
    result = rule.parse(source, "service.rs")
    assert len(result.classes) == 1
    assert result.classes[0].name == "OrderService"
    assert result.classes[0].kind == "struct"


def test_parse_enum(rule):
    source = b'''
enum Color {
    Red,
    Green,
    Blue,
}
'''
    result = rule.parse(source, "color.rs")
    enums = [c for c in result.classes if c.kind == "enum"]
    assert len(enums) == 1
    assert enums[0].name == "Color"


def test_parse_trait(rule):
    source = b'''
trait Drawable {
    fn draw(&self);
}
'''
    result = rule.parse(source, "drawable.rs")
    traits = [c for c in result.classes if c.kind == "trait"]
    assert len(traits) == 1
    assert traits[0].name == "Drawable"


def test_parse_trait_bodyless_method_is_captured(rule):
    """Required (bodyless) trait methods must be parsed, not silently dropped."""
    source = b'''pub trait AsyncRead {
    fn poll_read(&mut self) -> bool;
    fn default_method(&self) -> u32 { 0 }
}
'''
    result = rule.parse(source, "async_read.rs")
    fn_names = {f.name for f in result.functions}
    assert "poll_read" in fn_names, f"bodyless method missing: {fn_names}"
    assert "default_method" in fn_names


def test_trait_method_inherits_exported(rule):
    """Methods inside pub trait inherit the trait's exported status."""
    source = b'''pub trait Foo {
    fn required(&self);
    fn default_impl(&self) -> u32 { 0 }
}
'''
    result = rule.parse(source, "foo.rs")
    for fn in result.functions:
        assert fn.is_exported is True, f"{fn.name} should be exported (inherits trait)"


def test_parse_inline_module(rule):
    """Items inside `pub mod api { ... }` must be parsed, not dropped."""
    source = b'''pub mod api {
    pub fn handler() -> u32 { 42 }
    pub struct Config { name: String }
}
'''
    result = rule.parse(source, "lib.rs")
    fn_names = {f.name for f in result.functions}
    cls_names = {c.name for c in result.classes}
    assert "handler" in fn_names, f"inline mod function missing: {fn_names}"
    assert "Config" in cls_names, f"inline mod struct missing: {cls_names}"


def test_parse_nested_inline_module(rule):
    """Nested inline modules must be recursed into."""
    source = b'''pub mod outer {
    pub fn outer_fn() {}
    pub mod inner {
        pub fn inner_fn() {}
    }
}
'''
    result = rule.parse(source, "lib.rs")
    fn_names = {f.name for f in result.functions}
    assert "outer_fn" in fn_names
    assert "inner_fn" in fn_names


def test_inline_module_same_name_classes_get_distinct_module_path(rule):
    """Two structs named Body in different inline modules must have distinct module_path."""
    source = b'''pub mod sync_impl {
    pub struct Body { data: Vec<u8> }
}
pub mod async_impl {
    pub struct Body { data: Vec<u8> }
}
'''
    result = rule.parse(source, "lib.rs")
    assert len(result.classes) == 2
    paths = {c.module_path for c in result.classes}
    assert paths == {"sync_impl", "async_impl"}


def test_cfg_test_inline_module_propagates_to_inner_symbols(rule):
    """Items inside #[cfg(test)] mod must be marked as test context."""
    source = b'''pub fn public_fn() -> u32 { 1 }

#[cfg(test)]
mod tests {
    pub fn create_new() -> u32 { 0 }
    pub struct TestFuture;
}
'''
    result = rule.parse(source, "async_pool.rs")
    create_new = next(f for f in result.functions if f.name == "create_new")
    assert create_new.is_test is True
    test_future = next(c for c in result.classes if c.name == "TestFuture")
    assert "test" in test_future.cfg_conditions
    # public_fn outside the test module must NOT be marked test
    pub = next(f for f in result.functions if f.name == "public_fn")
    assert pub.is_test is False


def test_private_inline_module_symbols_not_exported(rule):
    """Items inside a non-pub ``mod private { ... }`` must not be exported."""
    source = b'''pub mod api {
    pub fn handler() {}
}
mod private {
    pub struct IndexSealed;
    pub fn helper() {}
}
'''
    result = rule.parse(source, "lib.rs")
    api_fn = next(f for f in result.functions if f.name == "handler")
    assert api_fn.is_exported is True
    priv_fn = next(f for f in result.functions if f.name == "helper")
    assert priv_fn.is_exported is False
    priv_cls = next(c for c in result.classes if c.name == "IndexSealed")
    assert priv_cls.is_exported is False


def test_impl_methods_get_module_path(rule):
    """Methods inside inline module impl blocks get the module's path."""
    source = b'''pub mod sync_impl {
    pub struct Body;
    impl Body {
        pub fn sync_method(&self) {}
    }
}
pub mod async_impl {
    pub struct Body;
    impl Body {
        pub fn async_method(&self) {}
    }
}
'''
    result = rule.parse(source, "lib.rs")
    sync_m = next(f for f in result.functions if f.name == "sync_method")
    async_m = next(f for f in result.functions if f.name == "async_method")
    assert sync_m.module_path == "sync_impl"
    assert async_m.module_path == "async_impl"


def test_pub_use_records_reexport_names(rule):
    """``pub use util::Entry;`` should record 'Entry' as a re-exported name."""
    source = b'''mod util;
pub use util::Entry;
pub use util::helper as do_help;
'''
    result = rule.parse(source, "lib.rs")
    assert "Entry" in result.reexported_names
    # Aliased re-export records the alias name
    assert "do_help" in result.reexported_names


def test_pub_mod_vs_private_mod_declaration(rule):
    """``pub mod api;`` records 'api' as pub, ``mod util;`` does not."""
    source = b'''pub mod api;
mod util;
'''
    result = rule.parse(source, "lib.rs")
    assert "api" in result.pub_mod_names
    assert "util" not in result.pub_mod_names


def test_parse_impl_methods(rule):
    source = b'''
impl OrderService {
    fn create_order(&self, items: Vec<String>) -> Result<(), Error> {
        Ok(())
    }
}
'''
    result = rule.parse(source, "service.rs")
    method_names = [f.name for f in result.functions]
    assert "create_order" in method_names


def test_parse_impl_methods_class_name(rule):
    source = b'''
impl OrderService {
    fn create_order(&self) -> Result<(), Error> {
        Ok(())
    }
}
'''
    result = rule.parse(source, "service.rs")
    fn = result.functions[0]
    assert fn.class_name == "OrderService"


def test_parse_use(rule):
    source = b'use std::collections::HashMap;'
    result = rule.parse(source, "main.rs")
    assert len(result.imports) >= 1
    imp = result.imports[0]
    assert "HashMap" in imp.symbols or "std::collections" in imp.module


def test_parse_use_with_braces(rule):
    source = b'use std::collections::{HashMap, HashSet};'
    result = rule.parse(source, "main.rs")
    assert len(result.imports) >= 1
    imp = result.imports[0]
    assert "HashMap" in imp.symbols
    assert "HashSet" in imp.symbols


def test_parse_test_function(rule):
    source = b'''
#[test]
fn test_hello() {
    assert_eq!(hello("world"), "Hello world");
}
'''
    result = rule.parse(source, "test.rs")
    test_fns = [f for f in result.functions if f.is_test]
    assert len(test_fns) >= 1
    assert test_fns[0].name == "test_hello"


def test_test_attribute_does_not_mark_later_functions(rule):
    result = rule.parse(
        b"#[test]\nfn first() {}\nfn helper() {}\n",
        "main.rs",
    )

    flags = {fn.name: fn.is_test for fn in result.functions}
    assert flags == {"first": True, "helper": False}


def test_trait_impl_methods_belong_to_concrete_type(rule):
    result = rule.parse(
        b"trait Worker { fn run(&self); }\n"
        b"struct Service;\n"
        b"impl Worker for Service { fn run(&self) {} }\n",
        "main.rs",
    )

    implementation = [fn for fn in result.functions if fn.class_name == "Service"]
    assert [fn.name for fn in implementation] == ["run"]


def test_parse_test_function_by_name(rule):
    source = b'''
fn test_something() {
    assert!(true);
}
'''
    result = rule.parse(source, "main.rs")
    test_fns = [f for f in result.functions if f.is_test]
    assert len(test_fns) >= 1
    assert test_fns[0].name == "test_something"


def test_parse_pub_function(rule):
    source = b'pub fn public_helper() -> i32 { 42 }'
    result = rule.parse(source, "lib.rs")
    fn = result.functions[0]
    assert fn.name == "public_helper"
    assert fn.visibility == "public"


def test_parse_private_function(rule):
    source = b'fn internal_helper() -> i32 { 42 }'
    result = rule.parse(source, "lib.rs")
    fn = result.functions[0]
    assert fn.name == "internal_helper"
    assert fn.visibility == "private"


def test_parse_function_calls(rule):
    source = b'''
fn process() {
    let result = helper();
    format_result(result);
    println!("{}", result);
}
'''
    result = rule.parse(source, "main.rs")
    fn = result.functions[0]
    assert "helper" in fn.calls
    assert "format_result" in fn.calls


def test_parse_empty_file(rule):
    source = b''
    result = rule.parse(source, "empty.rs")
    assert len(result.functions) == 0
    assert len(result.classes) == 0
    assert len(result.imports) == 0


def test_parse_struct_pub(rule):
    source = b'''
pub struct PublicService {
    name: String,
}
'''
    result = rule.parse(source, "service.rs")
    cls = result.classes[0]
    assert cls.name == "PublicService"
    assert cls.visibility == "public"


def test_parse_multiple_impls(rule):
    source = b'''
impl Foo {
    fn bar(&self) {}
}

impl Baz {
    fn qux(&self) {}
}
'''
    result = rule.parse(source, "main.rs")
    method_names = [f.name for f in result.functions]
    assert "bar" in method_names
    assert "qux" in method_names
    bar_fn = [f for f in result.functions if f.name == "bar"][0]
    qux_fn = [f for f in result.functions if f.name == "qux"][0]
    assert bar_fn.class_name == "Foo"
    assert qux_fn.class_name == "Baz"


def test_parse_impl_self_call_resolved(rule):
    source = b'''
struct Mutex;
impl Mutex {
    fn lock(&self) {
        self.acquire();
    }
    fn acquire(&self) {}
}
'''
    result = rule.parse(source, "m.rs")
    lock_fn = [f for f in result.functions if f.name == "lock"][0]
    assert "Mutex::acquire" in lock_fn.calls
    assert not any(c.startswith("?.") for c in lock_fn.calls)


def test_parse_external_method_call_marked_unknown(rule):
    source = b'''
fn work(m: Mutex) {
    m.lock();
}
'''
    result = rule.parse(source, "main.rs")
    work_fn = result.functions[0]
    assert "?.lock" in work_fn.calls


def test_parse_return_type_excludes_where(rule):
    source = b'fn spawn<T>(t: T) -> JoinHandle<T::Output>\r\n    where\r\n        T: Future + Send,\r\n{\r\n    unimplemented!()\r\n}\r\n'
    result = rule.parse(source, "m.rs")
    fn = result.functions[0]
    assert fn.return_type == "JoinHandle<T::Output>"
    assert "where" not in (fn.return_type or "")
    assert "\r" not in (fn.signature or "")


def test_rust_is_exported(rule):
    source = b'''
pub fn public_fn() {}
pub(crate) fn crate_fn() {}
fn private_fn() {}
pub struct PubStruct;
struct PrivStruct;
'''
    result = rule.parse(source, "m.rs")
    fns = {f.name: f.is_exported for f in result.functions}
    assert fns["public_fn"] is True
    assert fns["crate_fn"] is False
    assert fns["private_fn"] is False
    classes = {c.name: c.is_exported for c in result.classes}
    assert classes["PubStruct"] is True
    assert classes["PrivStruct"] is False


def test_rust_cfg_conditions(rule):
    """#[cfg(feature = "...")] is captured as cfg_conditions on symbols."""
    source = b'''#[cfg(feature = "udp")]
pub fn udp_handler() {}

#[cfg(any(feature = "a", feature = "b"))]
pub fn multi_feature() {}

#[cfg(unix)]
pub fn unix_only() {}

pub fn always_present() {}

#[cfg(feature = "ffrt")]
pub struct FfrtTask;
'''
    result = rule.parse(source, "m.rs")
    fn_conds = {f.name: f.cfg_conditions for f in result.functions}
    cls_conds = {c.name: c.cfg_conditions for c in result.classes}

    assert fn_conds["udp_handler"] == ["feature:udp"]
    assert fn_conds["multi_feature"] == ["feature:a", "feature:b"]
    assert fn_conds["unix_only"] == ["unix"]
    assert fn_conds["always_present"] == []
    assert cls_conds["FfrtTask"] == ["feature:ffrt"]


def test_rust_cfg_use_reexport(rule):
    """pub use under #[cfg(feature)] carries cfg_conditions on the import."""
    source = b'''#[cfg(feature = "udp")]
pub use sys::{ConnectedUdpSocket, UdpSocket};

pub use sys::{Event, Events};
'''
    result = rule.parse(source, "m.rs")
    imports = {(i.module, tuple(i.symbols)): i.cfg_conditions for i in result.imports}
    # The gated re-export carries the feature; the plain one does not.
    gated = imports.get(("sys", ("ConnectedUdpSocket", "UdpSocket")))
    plain = imports.get(("sys", ("Event", "Events")))
    assert gated == ["feature:udp"]
    assert plain == []


def test_rust_generic_impl_uses_base_class_owner(rule):
    source = b'''pub struct Holder<T>(T);
impl<T> Holder<T> {
    pub fn get(&self) {}
}
'''

    result = rule.parse(source, "generic.rs")

    method = next(function for function in result.functions if function.name == "get")
    assert method.class_name == "Holder"


def test_rust_test_and_cfg_attributes_allow_intervening_comments(rule):
    source = b'''#[test]
// Documents the test.
fn works() {}

#[cfg(feature = "udp")]
/* Documents the gated function. */
fn udp_only() {}
'''

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

    assert functions["works"].is_test is True
    assert functions["udp_only"].cfg_conditions == ["feature:udp"]


def test_rust_cfg_survives_other_attributes_and_comments(rule):
    source = b'''#[cfg(feature = "slow")]
#[test]
// Explains why this conditional test exists.
fn target() {}
'''

    result = rule.parse(source, "stacked_attributes.rs")
    target = next(function for function in result.functions if function.name == "target")

    assert target.is_test is True
    assert target.cfg_conditions == ["feature:slow"]


def test_rust_collects_item_field_variant_macro_and_closure_evidence(rule):
    source = b'''pub const LIMIT: usize = 3;
pub static ENABLED: bool = true;
pub type UserId = u64;
macro_rules! ping { () => {} }

pub struct User {
    pub name: String,
    age: u8,
}

pub enum State { Ready, Failed(i32) }

fn build() {
    let handler = || 1;
}
'''
    result = rule.parse(source, "model.rs")
    symbols = {(symbol.kind, symbol.name): symbol for symbol in result.symbols}

    assert symbols[("constant", "LIMIT")].data_type == "usize"
    assert ("static", "ENABLED") in symbols
    assert ("type_alias", "UserId") in symbols
    assert ("macro", "ping") in symbols
    assert symbols[("field", "name")].owner_name == "User"
    assert symbols[("field", "age")].is_exported is False
    assert symbols[("enum_variant", "Ready")].owner_name == "State"
    assert symbols[("closure_binding", "handler")].owner_name == "build"
    assert result.parser_name == "tree-sitter-rust"
    assert result.parse_status == "ok"
    assert result.functions[0].byte_start is not None
    assert result.classes[0].byte_end is not None


def test_rust_recovers_complete_items_with_diagnostics(rule):
    result = rule.parse(b"pub const GOOD: i32 = 1;\nfn broken(\n", "broken.rs")

    assert any(symbol.name == "GOOD" for symbol in result.symbols)
    assert result.parse_status == "recovered"
    assert result.parse_coverage < 1.0
    assert result.diagnostics