"""Tests for call graph cycle detection."""

from __future__ import annotations

from pathlib import Path
import tempfile

from vibelexity.call_graph import build_call_graph, find_call_cycles


def test_recursive_cycle():
    code = """
def foo():
    return foo()
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write(code)
        f.flush()

        graph = build_call_graph([Path(f.name)])
        cycles = find_call_cycles(graph)

        assert len(cycles) > 0

        Path(f.name).unlink()


def test_mutual_recursion():
    code = """
def foo():
    return bar()

def bar():
    return foo()
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write(code)
        f.flush()

        graph = build_call_graph([Path(f.name)])
        cycles = find_call_cycles(graph)

        assert len(cycles) > 0

        Path(f.name).unlink()


def test_no_cycle():
    code = """
def foo():
    return bar()

def bar():
    return 42

def baz():
    return 1
"""
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write(code)
        f.flush()

        graph = build_call_graph([Path(f.name)])
        cycles = find_call_cycles(graph)

        assert len(cycles) == 0

        Path(f.name).unlink()
