import sys
import shutil
import subprocess
import importlib

def install_package(cmd):
    """Install a pip package if missing."""
    print(f"'{cmd}' not found, installing via pip...")
    subprocess.run([sys.executable, "-m", "pip", "install", cmd], check=True)

def run_cli(cmd, args):
    """Run a command line executable."""
    if shutil.which(cmd) is None:
        install_package(cmd)
    subprocess.run([cmd] + args)

def run_library(package, code=None):
    """Run Python library code or just check library exists."""
    try:
        importlib.import_module(package)
    except ModuleNotFoundError:
        install_package(package)

    if code:
        exec(code, globals())
    else:
        print(f"Library '{package}' is installed. No CLI available.")

def main():
    import argparse
    parser = argparse.ArgumentParser(description="Caki: auto-install CLI or Python packages")
    parser.add_argument("target", help="Command name or package name")
    parser.add_argument("args", nargs="*", help="Arguments for command or Python code")
    parser.add_argument("-v", "--version", action="version", version="caki 0.3.0")
    opts = parser.parse_args()

    target = opts.target
    args = opts.args

    # Auto-detect CLI vs library
    if shutil.which(target):
        run_cli(target, args)
    else:
        code = " ".join(args) if args else None
        run_library(target, code)