import os
import pytest
import tempfile
import sys

# Add the parent directory to the Python path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

# Adjust the import based on the correct module structure
from reqgenz.src.reqgenz import RequirementsGenerator

@pytest.fixture
def setup_directories():
    # Create temporary directories for source and output
    with tempfile.TemporaryDirectory() as source_dir, tempfile.TemporaryDirectory() as output_dir:
        yield source_dir, output_dir

def test_find_python_files(setup_directories):
    source_dir, output_dir = setup_directories
    # Create a sample Python file
    sample_file = os.path.join(source_dir, 'test_script.py')
    with open(sample_file, 'w') as f:
        f.write("import os\n")
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    generator.find_python_files()
    assert sample_file in generator.python_files

def test_extract_imports_from_file(setup_directories):
    source_dir, output_dir = setup_directories
    sample_file = os.path.join(source_dir, 'test_script.py')
    with open(sample_file, 'w') as f:
        f.write("import os\nfrom sys import path\n")

    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    imports = generator.extract_imports_from_file(sample_file)

    assert "os" in imports
    assert "sys" in imports

def test_generate_requirements_txt(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    generator.imports = {"numpy", "pandas"}
    generator.pinned_versions = {"numpy": "1.21.0", "pandas": "1.3.0"}
    
    generator.generate_requirements_txt()
    
    with open(os.path.join(output_dir, 'requirements.txt'), 'r') as f:
        content = f.read()
    
    assert "# This file was auto-generated by RequirementsGenerator" in content
    assert "numpy==1.21.0" in content
    assert "pandas==1.3.0" in content

def test_create_pyproject(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir, project_name="TestProject",package_manager="poetry", pinned_versions={"numpy": "1.21.0", "pandas": "1.3.0"})

    # Create a sample Python file with imports
    sample_file = os.path.join(source_dir, 'test_script.py')
    with open(sample_file, 'w') as f:
        f.write("import numpy\nimport pandas\nprint('Hello World')")  # Add imports to be detected

    # Create the pyproject.toml file
    generator.generate_requirements(create_pyproject=True, create_reqs_file=True, skip_install=True)
    
    with open(os.path.join(output_dir, 'pyproject.toml'), 'r') as f:
        content = f.read()
        
        # Check for expected content directly
        assert 'name = "TestProject"' in content
        assert 'numpy = "1.21.0"' in content
        assert 'pandas = "1.3.0"' in content


def test_create_pipfile(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    generator.imports = {"numpy", "pandas"}
    generator.pinned_versions = {"numpy": "1.21.0", "pandas": "1.3.0"}
    
    generator.create_pipfile()
    
    with open(os.path.join(output_dir, 'Pipfile'), 'r') as f:
        content = f.read()
    
    assert "[[source]]" in content
    assert '"numpy" = "1.21.0"' in content
    assert '"pandas" = "1.3.0"' in content

# New test cases

def test_empty_source_directory(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    generator.find_python_files()
    assert generator.python_files == []  # Should be empty

def test_no_imports_in_file(setup_directories):
    source_dir, output_dir = setup_directories
    sample_file = os.path.join(source_dir, 'test_script.py')
    with open(sample_file, 'w') as f:
        f.write("print('Hello World')\n")  # No imports

    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    imports = generator.extract_imports_from_file(sample_file)

    assert imports == set()  # Should be empty

def test_invalid_python_file(setup_directories):
    source_dir, output_dir = setup_directories
    sample_file = os.path.join(source_dir, 'invalid_script.txt')
    with open(sample_file, 'w') as f:
        f.write("This is not a Python file.\n")

    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    imports = generator.extract_imports_from_file(sample_file)

    assert imports == set()  # Should be empty

def test_increment_version_major(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir, project_name="TestProject")
    
    # Create a sample pyproject.toml
    pyproject_content = """
# This file was auto-generated by RequirementsGenerator
[tool.poetry]
name = "TestProject"
version = "1.0.0"
"""
    with open(os.path.join(output_dir, 'pyproject.toml'), 'w') as f:
        f.write(pyproject_content)

    generator.increment_version('major')

    with open(os.path.join(output_dir, 'pyproject.toml'), 'r') as f:
        content = f.read()

    assert 'version = "2.0.0"' in content

def test_increment_version_minor(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir, project_name="TestProject")
    
    # Create a sample pyproject.toml
    pyproject_content = """
# This file was auto-generated by RequirementsGenerator
[tool.poetry]
name = "TestProject"
version = "1.0.0"
"""
    with open(os.path.join(output_dir, 'pyproject.toml'), 'w') as f:
        f.write(pyproject_content)

    generator.increment_version('minor')

    with open(os.path.join(output_dir, 'pyproject.toml'), 'r') as f:
        content = f.read()

    assert 'version = "1.1.0"' in content

def test_increment_version_patch(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir, project_name="TestProject")
    
    # Create a sample pyproject.toml
    pyproject_content = """
# This file was auto-generated by RequirementsGenerator
[tool.poetry]
name = "TestProject"
version = "1.0.0"
"""
    with open(os.path.join(output_dir, 'pyproject.toml'), 'w') as f:
        f.write(pyproject_content)

    generator.increment_version('patch')

    with open(os.path.join(output_dir, 'pyproject.toml'), 'r') as f:
        content = f.read()

    assert 'version = "1.0.1"' in content

# Additional test cases

def test_find_python_files_no_python_files(setup_directories):
    source_dir, output_dir = setup_directories
    # Create a sample text file instead of a Python file
    sample_file = os.path.join(source_dir, 'test_script.txt')
    with open(sample_file, 'w') as f:
        f.write("This is a text file.\n")
    
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    generator.find_python_files()
    assert generator.python_files == []  # Should be empty

def test_extract_imports_from_empty_file(setup_directories):
    source_dir, output_dir = setup_directories
    sample_file = os.path.join(source_dir, 'empty_script.py')
    with open(sample_file, 'w') as f:
        f.write("")  # Empty file

    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    imports = generator.extract_imports_from_file(sample_file)

    assert imports == set()  # Should be empty

def test_increment_version_invalid_level(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir, project_name="TestProject")
    
    # Create a sample pyproject.toml
    pyproject_content = """
# This file was auto-generated by RequirementsGenerator
[tool.poetry]
name = "TestProject"
version = "1.0.0"
"""
    with open(os.path.join(output_dir, 'pyproject.toml'), 'w') as f:
        f.write(pyproject_content)

    # Attempt to increment with an invalid level
    generator.increment_version('invalid_level')  # Should log an error

def test_create_pyproject_with_no_imports(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir, project_name="TestProject", package_manager="poetry")
    
    # Create a sample Python file with no imports
    sample_file = os.path.join(source_dir, 'empty_script.py')
    with open(sample_file, 'w') as f:
        f.write("print('Hello World')\n")  # No imports

    # Create the pyproject.toml file with no imports
    generator.generate_requirements(create_pyproject=True,skip_install=True)  # Ensure this line is present
    
    with open(os.path.join(output_dir, 'pyproject.toml'), 'r') as f:
        content = f.read()
    
    assert "[tool.poetry]" in content
    assert 'name = "TestProject"' in content
    assert 'version = "0.1.0"' in content  # Default version

def test_create_pipfile_with_no_imports(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    
    generator.create_pipfile()
    
    with open(os.path.join(output_dir, 'Pipfile'), 'r') as f:
        content = f.read()
    
    assert "[[source]]" in content
    assert "[packages]" in content
    assert '"" = "*"' in content  # No packages should default to wildcard

def test_merge_requirements_with_conflict_resolution(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    
    # Create a requirements.txt with a conflicting version
    existing_requirements = """
numpy==1.19.0
pandas==1.1.0
# This file was auto-generated by RequirementsGenerator
"""
    with open(os.path.join(output_dir, 'requirements.txt'), 'w') as f:
        f.write(existing_requirements)

    generator.imports = {"numpy", "pandas"}
    generator.pinned_versions = {"numpy": "1.21.0", "pandas": "1.3.0"}
    
    merged_requirements = generator.merge_requirements(generator.imports)
    
    assert "numpy==1.21.0" in merged_requirements  # Should take the pinned version
    assert "pandas==1.3.0" in merged_requirements  # Should take the pinned version

def test_visualize_dependency_graph_no_dependencies(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(source_directory=source_dir, output_directory=output_dir)
    
    # No imports to visualize
    generator.visualize_dependency_graph()
    
    # Check if the output file is created
    assert os.path.exists(os.path.join(output_dir, 'dependency_graph.png'))

# Add more tests as needed for other methods

def test_create_virtual_env(setup_directories):
    source_dir, output_dir = setup_directories
    generator = RequirementsGenerator(
        source_directory=source_dir,
        output_directory=output_dir,
        env_name="test_env",
        python_env_version=["python3.12"],
        use_virtual_env=True,

    )
    # Create the virtual environment
    for python_version in generator.python_env_version:
        generator.create_virtual_env(python_version=python_version)

    # Check if the virtual environment directory exists
    # Log the path for debugging
    print(f"Checking for virtual environment at: {generator.env_path}")

    assert os.path.exists(generator.env_path), "Virtual environment directory should exist."
