import os
from pathlib import Path
import getpass
from colorama import Fore

ENV_NAME = "MALWARE_SENTINEL_API_KEY"
CONFIG_DIR = Path.home() / ".config" / "malware-sentinel"
CONFIG_FILE = CONFIG_DIR / "config.env"


def get_api_key():
    key = os.getenv(ENV_NAME)
    if key:
        print(Fore.GREEN + "API key loaded from environment.")
        return key

    if CONFIG_FILE.exists():
        for line in CONFIG_FILE.read_text().splitlines():
            if line.startswith(f"{ENV_NAME}="):
                print(Fore.GREEN + "API key loaded from saved file.")
                return line.split("=", 1)[1].strip()

    print(Fore.YELLOW + "No saved API key found.")
    key = getpass.getpass("Please enter your VirusTotal API key: ").strip()
    if not key:
        return None

    save_api_key(key)
    return key


def save_api_key(key):
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    CONFIG_FILE.write_text(f"{ENV_NAME}={key}\n")
    CONFIG_FILE.chmod(0o600)
    print(Fore.GREEN + "API key saved for future use.")
