import pytest
from ImportNinja.scanner import find_python_files, check_syntax, extract_imports_and_usage
from pathlib import Path
import os


@pytest.fixture
def temp_python_file(tmp_path):
    file = tmp_path / "test_file.py"
    file.write_text("""
import os
import sys
from math import sqrt

print(os.getcwd())
""")
    return file


@pytest.fixture
def temp_python_file_with_unused_import(tmp_path):
    file = tmp_path / "unused_imports.py"
    file.write_text("""
import json
import datetime

print("Hello World")
""")
    return file


@pytest.fixture
def temp_syntax_error_file(tmp_path):
    file = tmp_path / "syntax_error.py"
    file.write_text("""
import os
print(os.getcwd(
""")
    return file


def test_find_python_files(tmp_path, temp_python_file):
    found_files = find_python_files(tmp_path)
    assert temp_python_file in found_files


def test_check_syntax(temp_python_file, temp_syntax_error_file):
    assert check_syntax(temp_python_file) is True
    assert check_syntax(temp_syntax_error_file) is False


def test_extract_imports_and_usage(temp_python_file):
    imports, unused_imports = extract_imports_and_usage(temp_python_file)
    assert imports == {"os", "sys", "math"}
    assert unused_imports == {"sys", "math"}


def test_extract_imports_and_usage_with_unused_imports(temp_python_file_with_unused_import):
    imports, unused_imports = extract_imports_and_usage(temp_python_file_with_unused_import)
    assert imports == {"json", "datetime"}
    assert unused_imports == {"json", "datetime"}


def test_extract_imports_and_usage_with_no_imports(tmp_path):
    file = tmp_path / "no_imports.py"
    file.write_text("print(\"No imports here!\")")

    imports, unused_imports = extract_imports_and_usage(file)
    assert imports == set()
    assert unused_imports == set()
