"""Tests for database connection handling in log_features."""

import ast
import inspect
from pathlib import Path

from core.log_features.log_features import safe_log_features


def test_log_features_uses_thread_sensitive_false() -> None:
    """Verify thread_sensitive=False so concurrent calls get their own threads.

    thread_sensitive=True serializes all calls through one thread, creating a bottleneck.
    thread_sensitive=False allows parallel execution with one DB connection per thread.
    """
    log_features_path = Path(__file__).parent.parent.parent / "core" / "log_features" / "log_features.py"
    tree = ast.parse(log_features_path.read_text())

    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == "log_features":
            break
    else:
        raise AssertionError("Could not find log_features function")

    sync_to_async_decorator = None
    for decorator in node.decorator_list:
        if isinstance(decorator, ast.Call):
            func = decorator.func
            if (isinstance(func, ast.Name) and func.id == "sync_to_async") or (
                isinstance(func, ast.Attribute) and func.attr == "sync_to_async"
            ):
                sync_to_async_decorator = decorator
                break

    assert sync_to_async_decorator is not None, (
        "log_features should be decorated with @sync_to_async. "
        "Decorators found: " + ", ".join(ast.unparse(d) for d in node.decorator_list)
    )

    for keyword in sync_to_async_decorator.keywords:
        if keyword.arg == "thread_sensitive":
            assert isinstance(keyword.value, ast.Constant), (
                f"thread_sensitive should be a boolean constant, got {ast.unparse(keyword.value)}"
            )
            assert keyword.value.value is False, (
                f"thread_sensitive should be False, got {keyword.value.value!r}. "
                "True serializes all calls through one thread, causing a bottleneck."
            )
            break
    else:
        raise AssertionError(
            "@sync_to_async should have thread_sensitive=False. "
            "Current decorator: " + ast.unparse(sync_to_async_decorator)
        )


def test_safe_log_features_is_async() -> None:
    assert inspect.iscoroutinefunction(safe_log_features), "safe_log_features should be an async def"
