#!/usr/bin/env python3
"""
ReClaimor CLI - Command-line interface
"""
import asyncio
import sys
import json
from pathlib import Path
from typing import Optional

import click
from rich.console import Console
from rich.table import Table
from rich.progress import Progress

from reclaimor import __version__
from reclaimor.scanner.engine import Scanner
from reclaimor.config import Config
from reclaimor.output.reporter import Reporter
from reclaimor.utils.logger import setup_logger

console = Console()
logger = setup_logger(__name__)


BANNER = """
  [bold yellow]██████╗ ███████╗ ██████╗██╗      █████╗ ██╗███╗   ███╗ ██████╗ ██████╗ [/bold yellow]
  [bold yellow]██╔══██╗██╔════╝██╔════╝██║     ██╔══██╗██║████╗ ████║██╔═══██╗██╔══██╗[/bold yellow]
  [bold yellow]██████╔╝█████╗  ██║     ██║     ███████║██║██╔████╔██║██║   ██║██████╔╝[/bold yellow]
  [bold yellow]██╔══██╗██╔══╝  ██║     ██║     ██╔══██║██║██║╚██╔╝██║██║   ██║██╔══██╗[/bold yellow]
  [bold yellow]██║  ██║███████╗╚██████╗███████╗██║  ██║██║██║ ╚═╝ ██║╚██████╔╝██║  ██║[/bold yellow]
  [bold yellow]╚═╝  ╚═╝╚══════╝ ╚═════╝╚══════╝╚═╝  ╚═╝╚═╝╚═╝     ╚═╝ ╚═════╝ ╚═╝  ╚═╝[/bold yellow]

  [bold white]Advanced Subdomain Takeover Scanner[/bold white]
  [dim]Smart • Fast • Responsibly Built[/dim]

  [bold green]Author:[/bold green]  Lakshmikanthan (@letchupkt)
  [bold green]GitHub:[/bold green]  https://github.com/letchupkt
  [bold green]Version:[/bold green] 0.1.3

  [bold red]⚠️  Use only on authorized targets • Unauthorized scanning is illegal[/bold red]
"""


def show_banner():
    """Display cool banner with admin details."""
    console.print(BANNER)


@click.command()
@click.version_option(version=__version__)
@click.option("--url", "-u", help="Single URL/domain to scan")
@click.option("--file", "-f", "file_path", type=click.Path(exists=True), help="File containing domains (one per line)")
@click.option("--stdin", is_flag=True, help="Read domains from stdin")
@click.option("--output", "-o", help="Output file path")
@click.option("--format", "-F", type=click.Choice(["json", "csv", "html", "text"]), default="text", help="Output format")
@click.option("--concurrency", "-c", default=50, help="Number of concurrent requests")
@click.option("--timeout", "-t", default=15, help="Request timeout in seconds")
@click.option("--retries", "-r", default=3, help="Number of retries per request")
@click.option("--auto-exploit", is_flag=True, help="Enable auto-exploitation for verification (REQUIRES AUTHORIZATION)")
@click.option("--aggressive", is_flag=True, help="Enable aggressive mode (required with --auto-exploit)")
@click.option("--safe", is_flag=True, default=True, help="Safe mode - detection only (default)")
@click.option("--tui", is_flag=True, help="Launch interactive TUI for manual triage")
@click.option("--resume", type=click.Path(exists=True), help="Resume from checkpoint file")
@click.option("--webhook", help="Webhook URL for notifications (Slack/Discord)")
@click.option("--rate-limit", default=10, help="Max requests per second")
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
@click.option("--debug", is_flag=True, help="Debug mode")
@click.option("--self-check", is_flag=True, help="Run self-check and exit")
@click.option("--no-banner", is_flag=True, help="Skip banner display")
def main(
    url: Optional[str],
    file_path: Optional[str],
    stdin: bool,
    output: Optional[str],
    format: str,
    concurrency: int,
    timeout: int,
    retries: int,
    auto_exploit: bool,
    aggressive: bool,
    safe: bool,
    tui: bool,
    resume: Optional[str],
    webhook: Optional[str],
    rate_limit: int,
    verbose: bool,
    debug: bool,
    self_check: bool,
    no_banner: bool,
):
    """
    ReClaimor - Advanced subdomain takeover scanner
    
    Built by @letchu - https://github.com/letchupkt
    """
    
    # Self-check mode
    if self_check:
        from reclaimor.utils.selfcheck import run_self_check
        asyncio.run(run_self_check())
        return
    
    # Show banner unless explicitly skipped
    if not no_banner:
        show_banner()
    
    # Validate input
    if not url and not file_path and not stdin and not resume:
        console.print("[red]Error: Must provide --url, --file, --stdin, or --resume[/red]")
        sys.exit(1)
    
    # Validate auto-exploit requirements
    if auto_exploit and not aggressive:
        console.print("[red]Error: --auto-exploit requires --aggressive flag for safety[/red]")
        sys.exit(1)
    
    if auto_exploit:
        console.print("[bold yellow]⚠️  AUTO-EXPLOIT MODE ENABLED - Use responsibly![/bold yellow]")
    
    # Load configuration
    config = Config(
        concurrency=concurrency,
        timeout=timeout,
        retries=retries,
        auto_exploit=auto_exploit and aggressive,
        safe_mode=safe and not auto_exploit,
        rate_limit=rate_limit,
        webhook_url=webhook,
        verbose=verbose,
        debug=debug,
    )
    
    # Collect targets
    targets = []
    if url:
        targets.append(url)
    if file_path:
        with open(file_path, "r") as f:
            targets.extend([line.strip() for line in f if line.strip()])
    if stdin:
        targets.extend([line.strip() for line in sys.stdin if line.strip()])
    
    if not targets and not resume:
        console.print("[red]Error: No targets provided[/red]")
        sys.exit(1)
    
    console.print(f"[cyan]ReClaimor v{__version__}[/cyan]")
    console.print(f"[cyan]Scanning {len(targets)} target(s)...[/cyan]\n")
    
    # Run scanner
    try:
        results = asyncio.run(run_scan(targets, config, tui, resume))
        
        # Generate report
        reporter = Reporter(config)
        if output:
            reporter.save(results, output, format)
            console.print(f"\n[green]✓ Results saved to {output}[/green]")
        else:
            reporter.print_console(results)
        
        # Send webhook notification
        if webhook and results:
            asyncio.run(reporter.send_webhook(results, webhook))
        
    except KeyboardInterrupt:
        console.print("\n[yellow]Scan interrupted by user[/yellow]")
        sys.exit(130)
    except Exception as e:
        console.print(f"[red]Error: {e}[/red]")
        if debug:
            raise
        sys.exit(1)


async def run_scan(targets, config, tui_mode, resume_path):
    """Run the scanning process."""
    scanner = Scanner(config)
    
    if tui_mode:
        from reclaimor.ui.tui import TUI
        tui = TUI(scanner, targets)
        return await tui.run()
    else:
        results = []
        with Progress() as progress:
            task = progress.add_task("[cyan]Scanning...", total=len(targets))
            
            for target in targets:
                result = await scanner.scan(target)
                results.append(result)
                progress.update(task, advance=1)
                
                # Print immediate findings
                if result.vulnerable:
                    console.print(
                        f"[red]✗ VULNERABLE[/red] {result.domain} "
                        f"[yellow](confidence: {result.confidence}%)[/yellow] "
                        f"[dim]{result.provider}[/dim]"
                    )
        
        return results


if __name__ == "__main__":
    main()
