import os

import typer
from flashenv.config import DIRECTORY_PATH, PRIV_KEY_PATH, PUB_KEY_PATH
from flashenv.core.aws import upload_key_aws
from Crypto.PublicKey import RSA


def create_dir():
    try:
        os.makedirs(DIRECTORY_PATH, exist_ok=True)
        typer.secho(f"✅ Configuration directory '{DIRECTORY_PATH}' ready.", fg=typer.colors.GREEN)
    except PermissionError:
        typer.secho(f"❌ Permission denied: Unable to create '{DIRECTORY_PATH}'.", fg=typer.colors.RED)
    except Exception as e:
        typer.secho(f"❌ Error creating directory: {e}", fg=typer.colors.RED)
        raise typer.Exit(code=1) from None


def create_keys():
    private_key_path = PRIV_KEY_PATH
    public_key_path = PUB_KEY_PATH
    try:
        if public_key_path.exists():
            typer.secho(f"✅ RSA Key '{DIRECTORY_PATH}' already exists.", fg=typer.colors.GREEN)
            private_key_path.chmod(0o600)
            public_key_bytes = public_key_path.read_bytes()
            upload_key_aws(public_key=public_key_bytes)
        else:
            typer.echo("Generating RSA Key...")
            key = RSA.generate(2048)
            private_key = key.export_key()
            with open(private_key_path, "wb") as f:
                f.write(private_key)
            private_key_path.chmod(0o600)
            public_key = key.publickey().export_key(format="OpenSSH")
            with open(public_key_path, "wb") as f:
                f.write(public_key)
            typer.secho(f"✅ RSA Key created: '{private_key_path}' ready.", fg=typer.colors.GREEN)
            upload_key_aws(public_key=public_key)
    except Exception as e:
        typer.secho(f"❌ Error creating RSA key: {e}", fg=typer.colors.RED)
        raise typer.Exit(code=1) from None


def delete_local_keys():
    """Removes the local private and public keys."""
    files_paths = [PRIV_KEY_PATH, PUB_KEY_PATH]

    for file_path in files_paths:
        if file_path.exists():
            try:
                file_path.unlink()
                typer.secho(f"🗑️  Deleted local file: {file_path}", fg=typer.colors.YELLOW)
            except OSError as e:
                typer.secho(f'❌ Error deleting "{file_path}": {e}', fg=typer.colors.RED)
        else:
            typer.secho(f'💨 Local file "{file_path}" not found (already clean).', fg=typer.colors.BRIGHT_BLACK)


def check_init():
    """
    Checks if FlashEnv is initialized before running any 'env' command.
    """
    if not DIRECTORY_PATH.exists() or not PUB_KEY_PATH.exists():
        typer.secho("❌ FlashEnv is not initialized.", fg=typer.colors.RED, bold=True)
        typer.echo("Please run the following command first:")
        typer.secho("   flashenv init", fg=typer.colors.GREEN)
        raise typer.Exit(1)
