import click
import asyncio
from rich.console import Console
from rich.logging import RichHandler
import logging
import subprocess
import tempfile
import shutil
import os
from .engine import ScanEngine

# Configure logging
logging.basicConfig(
    level="INFO",
    format="%(message)s",
    datefmt="[%X]",
    handlers=[RichHandler(rich_tracebacks=True)]
)

log = logging.getLogger("dep-raptor")
console = Console()

from .utils.ui import UI

@click.group()
def cli():
    """
    dep-raptor: Multi-language CLI security tool for detecting dependency confusion.
    """
    UI.banner()
    pass

@cli.command()
@click.argument('target')
@click.option('--poc', is_flag=True, help='Generate safe PoC packages if vulnerabilities are found.')
def scan(target, poc):
    """Scan a directory or a Git URL for dependency confusion vulnerabilities."""
    if target.startswith(("http://", "https://", "git@")):
        console.print(f"[bold blue]Cloning repository:[/bold blue] {target}")
        tmp_dir = tempfile.mkdtemp(prefix="dep-raptor-")
        try:
            subprocess.run(["git", "clone", "--depth", "1", target, tmp_dir], check=True, capture_output=True)
            console.print(f"[bold green]Clone successful.[/bold green]")
            console.print(f"[bold blue]Scanning path:[/bold blue] {tmp_dir}")
            asyncio.run(run_scan(tmp_dir, poc))
        except subprocess.CalledProcessError as e:
            console.print(f"[bold red]Error cloning repository:[/bold red] {e.stderr.decode()}")
        finally:
            if os.path.exists(tmp_dir):
                shutil.rmtree(tmp_dir)
    else:
        if not os.path.exists(target):
            console.print(f"[bold red]Error:[/bold red] Path {target} does not exist.")
            return
        console.print(f"[bold blue]Scanning path:[/bold blue] {target}")
        if poc:
            console.print("[yellow]PoC mode enabled.[/yellow]")
        asyncio.run(run_scan(target, poc))

async def run_scan(path, poc):
    """Entry point for the async scanning logic."""
    log.info(f"Starting scan in {path}...")
    engine = ScanEngine()
    await engine.run(path, poc)

if __name__ == "__main__":
    cli()
