"""
OomLlama CLI - Command line interface.
"""

import argparse
import sys
from typing import Optional


def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(
        prog="oomllama",
        description="OomLlama - Smart LLM routing"
    )
    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # Generate command
    gen_parser = subparsers.add_parser("gen", help="Generate text")
    gen_parser.add_argument("prompt", nargs="*", help="Prompt text")
    gen_parser.add_argument("-m", "--model", default="qwen2.5:7b", help="Model name")
    gen_parser.add_argument("-t", "--temperature", type=float, default=0.7)
    gen_parser.add_argument("--max-tokens", type=int, default=512)
    gen_parser.add_argument("--auto", action="store_true", help="Auto-route to best model")
    gen_parser.add_argument("--url", default="http://localhost:11434", help="Ollama URL")

    # Chat command
    chat_parser = subparsers.add_parser("chat", help="Interactive chat")
    chat_parser.add_argument("-m", "--model", default="qwen2.5:7b", help="Model name")
    chat_parser.add_argument("--url", default="http://localhost:11434", help="Ollama URL")

    # List models
    list_parser = subparsers.add_parser("list", help="List available models")
    list_parser.add_argument("--url", default="http://localhost:11434", help="Ollama URL")

    # Status
    status_parser = subparsers.add_parser("status", help="Check Ollama status")
    status_parser.add_argument("--url", default="http://localhost:11434", help="Ollama URL")

    args = parser.parse_args()

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

    from .core import OomLlama

    if args.command == "gen":
        prompt = " ".join(args.prompt) if args.prompt else None

        if not prompt:
            # Read from stdin
            if not sys.stdin.isatty():
                prompt = sys.stdin.read().strip()
            else:
                print("Enter prompt (Ctrl+D to end):")
                prompt = sys.stdin.read().strip()

        if not prompt:
            print("Error: No prompt provided", file=sys.stderr)
            return 1

        llm = OomLlama(
            model=args.model,
            ollama_url=args.url,
            auto_route=args.auto
        )
        llm.temperature = args.temperature
        llm.max_tokens = args.max_tokens

        try:
            response = llm.generate(prompt)
            print(response)
        except Exception as e:
            print(f"Error: {e}", file=sys.stderr)
            return 1

        return 0

    if args.command == "chat":
        llm = OomLlama(model=args.model, ollama_url=args.url)

        print(f"OomLlama Chat ({args.model})")
        print("Type 'quit' to exit\n")

        messages = []

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

            if user_input.lower() in ["quit", "exit", "q"]:
                print("Bye!")
                break

            if not user_input:
                continue

            messages.append({"role": "user", "content": user_input})

            try:
                response = llm.chat(messages)
                print(f"OomLlama: {response}\n")
                messages.append({"role": "assistant", "content": response})
            except Exception as e:
                print(f"Error: {e}\n")

        return 0

    if args.command == "list":
        llm = OomLlama(ollama_url=args.url)

        if not llm.is_available():
            print(f"Error: Ollama not available at {args.url}", file=sys.stderr)
            return 1

        models = llm.list_models()
        print("Available models:")
        for m in models:
            print(f"  - {m}")

        return 0

    if args.command == "status":
        llm = OomLlama(ollama_url=args.url)

        if llm.is_available():
            models = llm.list_models()
            print(f"Ollama: Online ({args.url})")
            print(f"Models: {len(models)}")
        else:
            print(f"Ollama: Offline ({args.url})")
            return 1

        return 0

    return 0


if __name__ == "__main__":
    sys.exit(main())
