"""Terminal User Interface for interactive triage."""
import asyncio
from typing import List

from rich.console import Console
from rich.table import Table
from rich.prompt import Prompt

from reclaimor.scanner.engine import Scanner
from reclaimor.scanner.result import ScanResult

console = Console()


class TUI:
    """Interactive Terminal UI for manual triage."""
    
    def __init__(self, scanner: Scanner, targets: List[str]):
        self.scanner = scanner
        self.targets = targets
        self.results: List[ScanResult] = []
        self.current_index = 0
    
    async def run(self) -> List[ScanResult]:
        """Run interactive TUI."""
        console.print("[bold cyan]ReClaimor Interactive TUI[/bold cyan]\n")
        console.print(f"Scanning {len(self.targets)} targets...\n")
        
        # Scan all targets first
        async with self.scanner:
            for i, target in enumerate(self.targets, 1):
                console.print(f"[{i}/{len(self.targets)}] Scanning {target}...")
                result = await self.scanner.scan(target)
                self.results.append(result)
        
        # Interactive triage
        console.print("\n[green]Scan complete![/green] Starting interactive triage...\n")
        
        vulnerable = [r for r in self.results if r.vulnerable]
        
        if not vulnerable:
            console.print("[green]No vulnerabilities found![/green]")
            return self.results
        
        console.print(f"Found {len(vulnerable)} potentially vulnerable domains.\n")
        
        for i, result in enumerate(vulnerable, 1):
            self._display_result(result, i, len(vulnerable))
            
            action = Prompt.ask(
                "Action",
                choices=["n", "e", "s", "q"],
                default="n",
            )
            
            if action == "q":
                break
            elif action == "e" and self.scanner.exploiter:
                await self._exploit_target(result)
            elif action == "s":
                self._save_single(result)
            
            console.print("\n" + "=" * 80 + "\n")
        
        return self.results
    
    def _display_result(self, result: ScanResult, index: int, total: int):
        """Display detailed result information."""
        console.print(f"[bold]Result {index}/{total}[/bold]")
        console.print(f"Domain: [cyan]{result.domain}[/cyan]")
        console.print(f"Status: [red]VULNERABLE[/red]")
        console.print(f"Confidence: [yellow]{result.confidence}%[/yellow]")
        console.print(f"Provider: {result.provider or 'Unknown'}")
        
        if result.cname:
            console.print(f"CNAME: {result.cname}")
        
        if result.status_code:
            console.print(f"HTTP Status: {result.status_code}")
        
        if result.notes:
            console.print(f"Notes: {', '.join(result.notes)}")
        
        console.print("\nOptions:")
        console.print("  [n] Next")
        console.print("  [e] Exploit (verify)")
        console.print("  [s] Save to file")
        console.print("  [q] Quit")
    
    async def _exploit_target(self, result: ScanResult):
        """Attempt exploitation on target."""
        console.print("\n[yellow]Attempting exploitation...[/yellow]")
        
        # This would call the exploiter
        console.print("[red]Exploitation requires --auto-exploit flag at startup[/red]")
    
    def _save_single(self, result: ScanResult):
        """Save single result to file."""
        import json
        filename = f"{result.domain.replace('.', '_')}_result.json"
        
        with open(filename, "w") as f:
            json.dump(result.to_dict(), f, indent=2)
        
        console.print(f"[green]Saved to {filename}[/green]")
