import shutil

import boto3
import typer
from botocore.exceptions import ClientError
from flashenv.config import DIRECTORY_PATH, KEY_NAME, SG_NAME
from flashenv.core.aws import get_flashenv_instances
from rich.console import Console
from flashenv.utils.init import check_init

console = Console()


def nuke_command(
    force: bool = typer.Option(False, "--force", "-f", help="Force deletion without confirmation"),
):
    """
    Destroys all flashenv resources.
    """

    check_init()

    if not force:
        console.print("\n[bold red]⚠️  WARNING: DANGER ZONE[/bold red]")
        console.print("This command will permanently destroy:")
        console.print("  - All EC2 instances using 'flashenv-key'")
        console.print("  - The 'flashenv-sg' Security Group")
        console.print("  - The AWS Key Pair 'flashenv-key'")
        console.print("  - All local configuration files (~/.flashenv)")

        if not typer.confirm("Are you absolutely sure you want to proceed?"):
            console.print("Operation aborted.")
            raise typer.Exit()

    ec2 = boto3.client("ec2")

    try:
        console.print("\n[bold yellow]☢️  Initiating nuke process...[/bold yellow]")
        instance_ids = get_flashenv_instances(ec2)
        if instance_ids:
            console.print(f"🔫 Terminating {len(instance_ids)} instance(s)...")
            ec2.terminate_instances(InstanceIds=instance_ids)
            with console.status("[bold yellow]⏳ Waiting for instances to terminate (required for SG deletion)..."):
                waiter = ec2.get_waiter("instance_terminated")
                waiter.wait(InstanceIds=instance_ids)
            console.print("✅ All instances are terminated.")
        else:
            console.print("💨 No active instances found.")

        try:
            ec2.delete_key_pair(KeyName=KEY_NAME)
            console.print(f"✅ AWS Key Pair '{KEY_NAME}' deleted.")
        except ClientError:
            pass

        try:
            ec2.delete_security_group(GroupName=SG_NAME)
            console.print(f"✅ Security Group '{SG_NAME}' deleted.")
        except ClientError as e:
            if "InvalidGroup.NotFound" in str(e):
                console.print("✅ Security Group already deleted.")
            elif "DependencyViolation" in str(e):
                console.print("[red]❌ Could not delete Security Group: Instances are still attached.[/red]")
            else:
                console.print(f"[red]❌ Security Group Error: {e}[/red]")

        if DIRECTORY_PATH.exists():
            shutil.rmtree(DIRECTORY_PATH)
            console.print(f"🗑️  Local directory {DIRECTORY_PATH} removed.")

        console.print("\n[bold green]✅ Nuke complete. flashenv has been reset.[/bold green]")

    except Exception as e:
        console.print(f"[bold red]❌ Critical Error: {e}[/bold red]")
        raise typer.Exit(1) from None
