#!/usr/bin/env python3
"""
JSEye CLI - Enhanced Main Entry Point
"""

import os
import sys
import argparse
from pathlib import Path
from rich.console import Console
from rich.panel import Panel

from .banner import show_banner, show_performance_banner
from .installer import check_and_install_tools
from .pipeline import JSEyePipeline

console = Console()

def create_parser():
    """Create enhanced argument parser"""
    parser = argparse.ArgumentParser(
        description="JSEye v1.0.2 - High-Performance JavaScript Intelligence Framework",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  jseye -i subs.txt -o output                    # Full parallel pipeline
  jseye -i subs.txt -o output --js-only          # Stop after JS discovery
  jseye -i subs.txt -o output --no-secrets       # Skip secrets detection
  jseye -i subs.txt -o output --regex-only       # Only regex analysis
  jseye -i subs.txt -o output --performance      # Show performance banner
        """
    )
    
    # Required arguments
    parser.add_argument("-i", "--input", 
                       help="Input file containing subdomains")
    parser.add_argument("-o", "--output",
                       help="Output directory for results")
    
    # Performance and UI options
    parser.add_argument("--performance", action="store_true",
                       help="Show performance upgrades banner")
    parser.add_argument("--no-banner", action="store_true",
                       help="Skip banner display")
    
    # Module control flags
    parser.add_argument("--js-only", action="store_true",
                       help="Stop after JavaScript discovery")
    parser.add_argument("--no-install", action="store_true",
                       help="Do not auto-install missing tools")
    parser.add_argument("--skip-ast", action="store_true",
                       help="Skip AST analysis")
    parser.add_argument("--regex-only", action="store_true",
                       help="Only perform regex analysis")
    parser.add_argument("--no-secrets", action="store_true",
                       help="Skip secrets detection")
    parser.add_argument("--no-sinks", action="store_true",
                       help="Skip sink detection")
    parser.add_argument("--no-correlate", action="store_true",
                       help="Skip correlation engine")
    parser.add_argument("--list-modules", action="store_true",
                       help="Show available modules and exit")
    
    return parser

def list_modules():
    """List available modules with enhanced display"""
    modules_info = [
        ("harvest", "Parallel URL harvesting (gau, waybackurls, katana, hakrawler, subjs)", "[*]"),
        ("js_filter", "Intelligent JavaScript filtering with prioritization", "[>]"),
        ("js_download", "Parallel JavaScript file downloading with caching", "[>>]"),
        ("tiered_analysis", "Smart tiered analysis engine (T1/T2/T3)", "[#]"),
        ("analyze_regex", "Regex-based pattern analysis", "[~]"),
        ("analyze_ast", "AST-based code analysis", "[^]"),
        ("linkfinder", "Enhanced endpoint discovery", "[=]"),
        ("secrets", "Secret detection with mantra integration", "[!]"),
        ("sinks", "Vulnerability sink detection", "[?]"),
        ("correlate", "Intelligence correlation engine", "[<>]"),
        ("cache", "Comprehensive caching system", "[C]")
    ]
    
    console.print()
    panel_content = "[bold cyan]JSEye v1.0.2 - Available Modules[/bold cyan]\n\n"
    
    for name, desc, symbol in modules_info:
        panel_content += f"{symbol} [bold green]{name}[/bold green] - {desc}\n"
    
    panel = Panel(panel_content.strip(), style="cyan", title="[bold white]Module Overview[/bold white]")
    console.print(panel)
    console.print()

def validate_environment():
    """Validate the runtime environment"""
    issues = []
    
    # Check Python version
    if sys.version_info < (3, 10):
        issues.append("Python 3.10+ required")
    
    # Check write permissions for output
    try:
        test_dir = Path.cwd() / ".jseye_test"
        test_dir.mkdir(exist_ok=True)
        test_dir.rmdir()
    except:
        issues.append("No write permissions in current directory")
    
    return issues

def main():
    """Enhanced main CLI entry point"""
    parser = create_parser()
    args = parser.parse_args()
    
    # Show banner (unless disabled)
    if not args.no_banner:
        show_banner()
        if args.performance:
            show_performance_banner()
    
    # List modules if requested
    if args.list_modules:
        list_modules()
        return 0
    
    # Validate required arguments
    if not args.input or not args.output:
        console.print("[red]Error: Both --input and --output are required[/red]")
        parser.print_help()
        return 1
    
    # Validate environment
    env_issues = validate_environment()
    if env_issues:
        console.print("[red]Environment Issues:[/red]")
        for issue in env_issues:
            console.print(f"  • {issue}")
        return 1
    
    # Validate input file
    input_path = Path(args.input)
    if not input_path.exists():
        console.print(f"[red]Error: Input file '{args.input}' not found[/red]")
        return 1
    
    # Create output directory
    output_dir = Path(args.output)
    try:
        output_dir.mkdir(parents=True, exist_ok=True)
        console.print(f"[green]Output directory: {output_dir.absolute()}[/green]")
    except Exception as e:
        console.print(f"[red]Error creating output directory: {e}[/red]")
        return 1
    
    try:
        # Check and install tools if needed
        if not args.no_install:
            console.print("[yellow]Checking required tools...[/yellow]")
            if not check_and_install_tools():
                console.print("[red]Failed to install required tools[/red]")
                return 1
        
        # Initialize and run enhanced pipeline
        console.print("[bold cyan]Starting JSEye v1.0.2 High-Performance Pipeline...[/bold cyan]")
        pipeline = JSEyePipeline(args.input, args.output, args)
        results = pipeline.run()
        
        # Show enhanced summary
        pipeline.show_summary(results)
        
        console.print("[bold green][+] JSEye execution completed successfully![/bold green]")
        return 0
        
    except KeyboardInterrupt:
        console.print("\n[yellow][!] Interrupted by user[/yellow]")
        return 1
    except Exception as e:
        console.print(f"[red][-] Error: {e}[/red]")
        return 1

if __name__ == "__main__":
    sys.exit(main())