"""Self-check utility to verify tool dependencies and connectivity."""
import sys
import asyncio
from typing import List, Tuple

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

console = Console()


async def run_self_check():
    """Run comprehensive self-check."""
    console.print("[bold cyan]ReClaimor Self-Check[/bold cyan]\n")
    
    checks = [
        ("Python Version", check_python_version),
        ("Required Packages", check_packages),
        ("DNS Resolution", check_dns),
        ("HTTP Connectivity", check_http),
        ("Fingerprints", check_fingerprints),
    ]
    
    results = []
    
    for name, check_func in checks:
        console.print(f"Checking {name}...", end=" ")
        success, message = await check_func()
        results.append((name, success, message))
        
        if success:
            console.print("[green]✓[/green]")
        else:
            console.print("[red]✗[/red]")
    
    # Print summary table
    table = Table(title="Self-Check Results")
    table.add_column("Check", style="cyan")
    table.add_column("Status", justify="center")
    table.add_column("Details")
    
    for name, success, message in results:
        status = "[green]PASS[/green]" if success else "[red]FAIL[/red]"
        table.add_row(name, status, message)
    
    console.print("\n")
    console.print(table)
    
    all_passed = all(success for _, success, _ in results)
    if all_passed:
        console.print("\n[green]✓ All checks passed![/green]")
    else:
        console.print("\n[red]✗ Some checks failed. Please fix the issues above.[/red]")
        sys.exit(1)


async def check_python_version() -> Tuple[bool, str]:
    """Check Python version."""
    version = sys.version_info
    if version >= (3, 10):
        return True, f"Python {version.major}.{version.minor}.{version.micro}"
    return False, f"Python {version.major}.{version.minor} (requires 3.10+)"


async def check_packages() -> Tuple[bool, str]:
    """Check required packages."""
    required = ["aiohttp", "dns", "rich", "yaml", "click"]
    missing = []
    
    for package in required:
        try:
            __import__(package)
        except ImportError:
            missing.append(package)
    
    if missing:
        return False, f"Missing: {', '.join(missing)}"
    return True, "All packages installed"


async def check_dns() -> Tuple[bool, str]:
    """Check DNS resolution."""
    try:
        import dns.resolver
        resolver = dns.resolver.Resolver()
        resolver.resolve("google.com", "A")
        return True, "DNS resolution working"
    except Exception as e:
        return False, f"DNS error: {str(e)[:50]}"


async def check_http() -> Tuple[bool, str]:
    """Check HTTP connectivity."""
    try:
        import aiohttp
        async with aiohttp.ClientSession() as session:
            async with session.get("https://www.google.com", timeout=aiohttp.ClientTimeout(total=5)) as resp:
                if resp.status == 200:
                    return True, "HTTP connectivity working"
                return False, f"HTTP status: {resp.status}"
    except Exception as e:
        return False, f"HTTP error: {str(e)[:50]}"


async def check_fingerprints() -> Tuple[bool, str]:
    """Check fingerprints availability."""
    from pathlib import Path
    from reclaimor.fingerprints.loader import FingerprintLoader
    
    fp_dir = Path(__file__).parent.parent / "fingerprints"
    loader = FingerprintLoader(fp_dir)
    fingerprints = loader.load()
    
    if fingerprints:
        return True, f"{len(fingerprints)} fingerprints loaded"
    return False, "No fingerprints found"
