import sys
import shutil
import subprocess
import importlib

# Exceptions: CLI tool -> (install target, install instructions)
CLI_EXCEPTIONS = {
    "firebase": ("firebase-tools", "npm install -g firebase-tools"),
    "heroku": ("heroku", "npm install -g heroku"),
    "npm": (None, "Install Node.js from https://nodejs.org/"),
    "git": (None, "Install Git from https://git-scm.com/"),
    "aws": ("awscli", "pip install awscli"),
    "terraform": (None, "Download from https://www.terraform.io/downloads"),
    "yarn": ("yarn", "npm install -g yarn"),
    "docker": (None, "Install Docker from https://www.docker.com/get-started")
}

def install_package(package):
    """Auto-install Python package if missing."""
    try:
        importlib.import_module(package)
    except ModuleNotFoundError:
        print(f"'{package}' not found, installing via pip...")
        subprocess.run([sys.executable, "-m", "pip", "install", package], check=True)

def run_cli(cmd, args):
    """Run CLI command, auto-installing if in exceptions."""
    if cmd in CLI_EXCEPTIONS:
        install_target, instructions = CLI_EXCEPTIONS[cmd]
        if install_target:
            print(f"'{cmd}' CLI not found. Installing {install_target}...")
            if install_target.endswith("-tools") or install_target in ["heroku", "yarn"]:
                # Install via npm for known JS tools
                subprocess.run(["npm", "install", "-g", install_target], check=True)
            else:
                # Try pip for Python CLI tools
                subprocess.run([sys.executable, "-m", "pip", "install", install_target], check=True)
        else:
            print(f"'{cmd}' CLI not found. {instructions}")
            return
    elif shutil.which(cmd) is None:
        print(f"'{cmd}' CLI not found in PATH. Try installing it manually.")
        return

    # Run the CLI command
    subprocess.run([cmd] + args)

def run_library(package, code=None):
    """Auto-install Python package and execute code."""
    install_package(package)
    if code:
        exec(code, globals())
    else:
        print(f"Library '{package}' installed. No code to run.")

def main():
    import argparse
    parser = argparse.ArgumentParser(description="Caki: auto-install CLI or Python packages")
    parser.add_argument("target", help="Command or Python package to run")
    parser.add_argument("args", nargs="*", help="CLI arguments or Python code")
    parser.add_argument("--code", help="Python code to execute with library", default=None)
    parser.add_argument("-v", "--version", action="version", version="caki 0.5.0")
    args = parser.parse_args()

    target = args.target
    code = args.code
    extra_args = args.args

    # Auto-detect CLI vs library
    if shutil.which(target) or target in CLI_EXCEPTIONS:
        run_cli(target, extra_args)
    else:
        if code is None:
            # Join positional arguments as Python code
            code = " ".join(extra_args) if extra_args else None
        run_library(target, code)