from pathlib import Path
import sys
from typing import Set

def get_requirements_imports(requirements_file: str) -> Set[str]:
    """
    Get imports from a requirements file.
    Args:
        requirements_file (str): Path to the requirements file.
    Returns:
        set: A set of imports from the requirements file.
    """
    if not requirements_file or not Path(requirements_file).is_file():
        return set()
    with open(requirements_file, 'r', encoding='utf-8') as file:
        return set([line.strip() for line in file])
    
def check_requirements_file_up_to_date(requirements_imports: Set[str], all_imports: Set[str]) -> bool:
    """
    Check if the requirements file is up to date.
    Args:
        requirements_imports (set): A set of imports listed in the requirements.txt file.
        all_imports (set): A set of all imports found in the codebase.
    Returns:
        bool: A flag indicating if the requirements file is up to date.
    """
    return requirements_imports == all_imports

def requirements_file_analysis(requirements_imports: Set[str], all_imports: Set[str], requirements_file_up_to_date: bool=False) -> None:
    """
    Analyze the requirements file for missing or unused imports.
    Args:
        requirements_imports (set): A set of imports listed in the requirements.txt file.
        all_imports (set): A set of all imports found in the codebase.
        requirements_file_up_to_date (bool, optional): A flag indicating if the requirements file is up to date. Defaults to False.
    Returns:
        None
    """
    if not requirements_imports:
        print("\nNo requirements.txt file found.")
        return
    
    if requirements_file_up_to_date:
        print("\nRequirements file is up to date.")
        return
    print("\nRequirements file analysis:")
    imports_missing_in_requirements = all_imports - requirements_imports
    if imports_missing_in_requirements:
        print("\nImports missing in requirements.txt:")
        for imp in imports_missing_in_requirements:
            print(f"- {imp}")
    
    imports_not_used_but_in_requirements = requirements_imports - all_imports
    if imports_not_used_but_in_requirements:
        print("\nImports in requirements.txt not used:")
        for imp in imports_not_used_but_in_requirements:
            print(f"- {imp}")
            
def write_requirements_file(requirements_file: str, all_imports: Set[str]) -> None:
    """
    Write the imports to a requirements file.
    Args:
        requirements_file (str): Path to the requirements file.
        all_imports (set): A set of all imports found in the codebase.
    Returns:
        None
    """
    with open(requirements_file, 'w') as f:
        for imp in sorted(all_imports):
            if imp in sys.stdlib_module_names:
                continue
            f.write(f"{imp}\n")
    print(f"Requirements saved to {requirements_file}")