import argparse
from ImportNinja.scanner import find_python_files, check_syntax, extract_imports_and_usage
from ImportNinja.analyzer import get_requirements_imports, check_requirements_file_up_to_date, requirements_file_analysis, write_requirements_file
from ImportNinja.utils import print_counts, print_syntax_error_files, print_unused_imports, print_imports
from typing import Optional

def main() -> None:
    """
    Main function to run the ImportNinja CLI.
    
    This function parses the command line arguments and runs the scan on the specified directory.
    """
    parser = argparse.ArgumentParser(description="Scan Python project for dependencies.")
    parser.add_argument("directory", help="Directory to scan")
    parser.add_argument("-r", "--requirements", help="Requirements file to save dependencies")

    args = parser.parse_args()
    
    directory: str = args.directory
    requirements_file: Optional[str] = args.requirements if args.requirements else None
    
    requirements_imports = get_requirements_imports(requirements_file)
    all_imports = set()
    syntax_error_files = list()
    all_imports_with_duplicates = list()
    all_unused_imports = {}
    python_files = find_python_files(directory)

    print("Scanning for imports...")

    for file_path in python_files:
        if not check_syntax(file_path):
            syntax_error_files.append(file_path)
            continue
        imports, unused_imports = extract_imports_and_usage(file_path)
        all_imports.update(imports)
        all_imports_with_duplicates.extend(imports)
        
        if unused_imports:
            all_unused_imports[file_path] = unused_imports
            
    print_syntax_error_files(syntax_error_files)
    print_counts(python_files, all_imports, all_imports_with_duplicates, all_unused_imports)
    print_unused_imports(all_unused_imports)
    
    requirements_file_up_to_date = check_requirements_file_up_to_date(requirements_imports, all_imports)
    requirements_file_analysis(requirements_imports, all_imports, requirements_file_up_to_date)
    print_imports(all_imports)

    if requirements_file and not requirements_file_up_to_date:
        write_requirements_file(requirements_file, all_imports)
