#!/usr/bin/env python3
"""
JSEye CLI - Main entry point
"""

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

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

console = Console()

def clear_terminal():
    """Clear terminal screen (cross-platform)"""
    import platform
    if platform.system() == "Windows":
        os.system("cls")
    else:
        os.system("clear")

def create_parser():
    """Create argument parser"""
    parser = argparse.ArgumentParser(
        description="JSEye - JavaScript Intelligence & Attack Surface Discovery",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  jseye -i subs.txt -o output                    # Full pipeline (default)
  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
        """
    )
    
    # Required arguments (but not when listing modules)
    parser.add_argument("-i", "--input", 
                       help="Input file containing subdomains")
    parser.add_argument("-o", "--output",
                       help="Output directory for results")
    
    # Module control flags (disable/isolate modules)
    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 (mantra)")
    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"""
    modules = [
        "harvest - URL harvesting (gau, waybackurls, katana)",
        "js_filter - JavaScript file filtering",
        "js_download - JavaScript file downloading", 
        "analyze_regex - Regex-based analysis",
        "analyze_ast - AST-based analysis",
        "linkfinder - Endpoint discovery",
        "secrets - Secret detection (mantra)",
        "sinks - Sink detection",
        "correlate - Intelligence correlation"
    ]
    
    console.print("\n[bold cyan]Available JSEye Modules:[/bold cyan]")
    for module in modules:
        console.print(f"  • {module}")
    console.print()

def main():
    """Main CLI entry point"""
    parser = create_parser()
    args = parser.parse_args()
    
    # Clear terminal and show banner
    clear_terminal()
    show_banner()
    
    # List modules if requested
    if args.list_modules:
        list_modules()
        return 0
    
    # Validate required arguments for normal operation
    if not args.input or not args.output:
        parser.error("Input and output arguments are required for normal operation")
    
    # Validate input file
    if not Path(args.input).exists():
        console.print(f"[red]Error: Input file '{args.input}' not found[/red]")
        return 1
    
    # Create output directory
    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)
    
    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 pipeline
        pipeline = JSEyePipeline(args.input, args.output, args)
        results = pipeline.run()
        
        # Show summary
        pipeline.show_summary(results)
        
        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())