import os
from dotenv import load_dotenv
from src.scanner import ProjectScanner
from src.analyzer import CodeAnalyzer
from rich.console import Console

load_dotenv()
console = Console()

def main():
    # 1. Check API Key
    if not os.getenv("OPENROUTER_API_KEY"):
        console.print("[bold red]Error: OPENROUTER_API_KEY not found in .env file[/bold red]")
        return

    # 2. Get Project Path
    # Defaults to current directory, but can be passed as argument
    project_path = os.getenv("PROJECT_PATH", ".")
    
    if not os.path.exists(project_path):
        console.print(f"[bold red]Error: Path {project_path} does not exist[/bold red]")
        return

    # 3. Initialize Components
    scanner = ProjectScanner(project_path)
    analyzer = CodeAnalyzer()

    try:
        # 4. Scan Files
        files_data = scanner.scan()
        
        if not files_data:
            console.print("[yellow]No valid code files found to analyze.[/yellow]")
            return

        # 5. Run Analysis
        analyzer.run_full_audit(files_data)

    except KeyboardInterrupt:
        console.print("\n[bold yellow]Audit interrupted by user.[/bold yellow]")
    except Exception as e:
        console.print(f"[bold red]Critical Error: {e}[/bold red]")

if __name__ == "__main__":
    main()
