import pytest

from project_brain.build.languages.python import PythonRule


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


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


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


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


def test_extracts_ranged_relation_evidence_and_type_bindings(rule):
    source = b'''class User:
    def save(self):
        pass

def run(user: User):
    alias = User()
    user.save()
    user.name = alias.name
'''
    result = rule.parse(source, "main.py")
    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 == "user"
        for fact in run.references
    )
    assert {(binding.name, binding.type_name, binding.source) for binding in run.type_bindings} >= {
        ("user", "User", "parameter"),
        ("alias", "User", "constructor"),
    }


def test_extracts_explicit_ctypes_library_binding(rule):
    result = rule.parse(b'''import ctypes
lib = ctypes.CDLL("libnative.so")
def run():
    lib.native_save()
''', "ffi.py")
    run = next(function for function in result.functions if function.name == "run")
    binding = next(item for item in run.type_bindings if item.source == "ffi_library")

    assert binding.name == "lib"
    assert binding.foreign_library == "libnative.so"
    assert any(
        fact.kind == "call" and fact.name == "native_save" and fact.receiver == "lib"
        for fact in run.references
    )


def test_parse_simple_function(rule):
    source = b'''
def hello(name: str) -> str:
    """Say hello."""
    return f"Hello, {name}"
'''
    result = rule.parse(source, "main.py")
    assert len(result.functions) == 1
    fn = result.functions[0]
    assert fn.name == "hello"
    assert fn.line_start == 2
    assert fn.visibility == "public"
    assert fn.return_type == "str"
    assert fn.docstring == "Say hello."
    assert len(fn.params) == 1
    assert fn.params[0]["name"] == "name"
    assert fn.params[0]["type"] == "str"


def test_parse_async_function(rule):
    source = b'''
async def fetch_data(url: str):
    pass
'''
    result = rule.parse(source, "main.py")
    assert len(result.functions) == 1
    fn = result.functions[0]
    assert fn.name == "fetch_data"
    assert fn.is_async is True


def test_parse_private_function(rule):
    source = b'''
def _internal_helper():
    pass
'''
    result = rule.parse(source, "main.py")
    fn = result.functions[0]
    assert fn.name == "_internal_helper"
    assert fn.visibility == "private"


def test_parse_test_function(rule):
    source = b'''
def test_something():
    assert True
'''
    result = rule.parse(source, "test_main.py")
    fn = result.functions[0]
    assert fn.name == "test_something"
    assert fn.is_test is True


def test_parse_class(rule):
    source = b'''
class OrderService:
    """Handles orders."""

    def create_order(self, items: list) -> dict:
        return {"items": items}

    def _validate(self, order: dict):
        pass
'''
    result = rule.parse(source, "service.py")
    assert len(result.classes) == 1
    cls = result.classes[0]
    assert cls.name == "OrderService"
    assert cls.docstring == "Handles orders."
    assert len(cls.methods) == 2

    method_names = [f.name for f in result.functions]
    assert "create_order" in method_names
    assert "_validate" in method_names


def test_parse_class_with_bases(rule):
    source = b'''
class MyService(BaseService, Interface):
    pass
'''
    result = rule.parse(source, "service.py")
    cls = result.classes[0]
    assert "BaseService" in cls.bases
    assert "Interface" in cls.bases


def test_parse_imports(rule):
    source = b'''
import os
import sys
from pathlib import Path
from typing import Optional, List
'''
    result = rule.parse(source, "main.py")
    assert len(result.imports) == 4

    modules = [imp.module for imp in result.imports]
    assert "os" in modules
    assert "sys" in modules
    assert "pathlib" in modules
    assert "typing" in modules

    typing_imp = [imp for imp in result.imports if imp.module == "typing"][0]
    assert "Optional" in typing_imp.symbols
    assert "List" in typing_imp.symbols


def test_parse_function_calls(rule):
    source = b'''
def process():
    result = helper()
    other = format_result(result)
    print(result)
'''
    result = rule.parse(source, "main.py")
    fn = result.functions[0]
    assert "helper" in fn.calls
    assert "format_result" in fn.calls
    assert "print" in fn.calls


def test_parse_decorated_function(rule):
    source = b'''
@staticmethod
def static_method():
    pass
'''
    result = rule.parse(source, "main.py")
    assert len(result.functions) == 1


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


def test_parse_multiple_params(rule):
    source = b'''
def complex_func(a: int, b: str, c: list = None, *args, **kwargs):
    pass
'''
    result = rule.parse(source, "main.py")
    fn = result.functions[0]
    param_names = [p["name"] for p in fn.params]
    assert "a" in param_names
    assert "b" in param_names
    assert "c" in param_names


def test_parse_self_excluded_from_params(rule):
    source = b'''
class Foo:
    def method(self, x: int):
        pass
'''
    result = rule.parse(source, "main.py")
    fn = result.functions[0]
    param_names = [p["name"] for p in fn.params]
    assert "self" not in param_names
    assert "x" in param_names


def test_python_collects_value_and_attribute_evidence(rule):
    source = b'''LIMIT: int = 3
handler = lambda value: value

class User:
    category = "person"

    def __init__(self):
        self.name: str = "anonymous"
'''
    result = rule.parse(source, "models.py")
    symbols = {(symbol.kind, symbol.name): symbol for symbol in result.symbols}

    assert symbols[("module_variable", "LIMIT")].data_type == "int"
    assert ("lambda_binding", "handler") in symbols
    assert symbols[("class_attribute", "category")].owner_name == "User"
    assert symbols[("instance_attribute", "name")].owner_name == "User"
    assert symbols[("instance_attribute", "name")].data_type == "str"
    assert result.parser_name == "tree-sitter-python"
    assert result.parse_status == "ok"
    assert result.parse_coverage == 1.0
    assert result.functions[0].byte_start is not None
    assert result.classes[0].byte_end is not None


def test_python_recovers_useful_evidence_with_diagnostics(rule):
    result = rule.parse(b"VALUE = 1\ndef broken(:\n", "broken.py")

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


def test_python_decorators_are_callable_evidence(rule):
    result = rule.parse(b"@framework.route('/x')\ndef endpoint():\n    pass\n", "api.py")

    endpoint = next(function for function in result.functions if function.name == "endpoint")
    assert "route" in endpoint.calls