import argparse
import sys

from llamapass_cli import __version__
from llamapass_cli.client import chat_stream, list_models
from llamapass_cli.config import get, load, set_value


def cmd_run(args):
    model = args.model
    messages = []
    print(f"LlamaPass - {model} (type /bye to quit)\n")

    while True:
        try:
            user_input = input(">>> ")
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if user_input.strip().lower() in ("/bye", "/exit", "/quit"):
            print("Bye!")
            break

        if not user_input.strip():
            continue

        messages.append({"role": "user", "content": user_input})
        response = chat_stream(model, messages)
        if response:
            messages.append({"role": "assistant", "content": response})


def cmd_list(args):
    list_models()


def cmd_config(args):
    action = args.action

    if action == "show":
        cfg = load()
        print(f"  url:     {cfg['url']}")
        print(f"  api_key: {cfg['api_key'][:10]}..." if cfg["api_key"] else "  api_key: (not set)")

    elif action == "set-url":
        if not args.value:
            print("Usage: llamapass config set-url <url>")
            sys.exit(1)
        set_value("url", args.value)
        print(f"URL set to: {args.value}")

    elif action == "set-key":
        if not args.value:
            print("Usage: llamapass config set-key <key>")
            sys.exit(1)
        set_value("api_key", args.value)
        print(f"API key saved.")

    else:
        print(f"Unknown action: {action}")
        print("Available: show, set-url, set-key")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        prog="llamapass",
        description="CLI client for LlamaPass",
    )
    parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")

    subparsers = parser.add_subparsers(dest="command")

    # run
    run_parser = subparsers.add_parser("run", help="Chat with a model")
    run_parser.add_argument("model", help="Model name (e.g. gemma3)")

    # list
    subparsers.add_parser("list", help="List available models")
    subparsers.add_parser("ls", help="List available models")

    # config
    config_parser = subparsers.add_parser("config", help="Manage configuration")
    config_parser.add_argument("action", help="show | set-url | set-key")
    config_parser.add_argument("value", nargs="?", help="Value to set")

    args = parser.parse_args()

    if args.command is None:
        parser.print_help()
        sys.exit(0)

    commands = {
        "run": cmd_run,
        "list": cmd_list,
        "ls": cmd_list,
        "config": cmd_config,
    }
    commands[args.command](args)
