import argparse
import os
from dotenv import load_dotenv
import sys
from .client import Dracula
from .exceptions import DraculaException
from ._version import __version__

load_dotenv()


def main():
    parser = argparse.ArgumentParser(
        prog="dracula", description="🧛 Dracula — A simple CLI for Google Gemini"
    )

    parser.add_argument(
        "--version", action="version", version=f"Dracula v{__version__}"
    )

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

    # chat commands
    chat_parser = subparsers.add_parser("chat", help="Send a message to Gemini")
    chat_parser.add_argument("message", type=str, help="Message to send")
    chat_parser.add_argument("--persona", type=str, default=None, help="Persona to use")
    chat_parser.add_argument(
        "--language", type=str, default="Auto", help="Response language"
    )
    chat_parser.add_argument(
        "--temperature", type=float, default=1.0, help="Temperature (0.0 - 2.0)"
    )
    chat_parser.add_argument(
        "--stream", action="store_true", help="Stream the response"
    )

    # list-personas command
    subparsers.add_parser("list-personas", help="List all available personas")

    # stats command
    subparsers.add_parser("stats", help="Show usage stats")

    # clear-stats command
    subparsers.add_parser("clear-stats", help="Reset usage stats")

    args = parser.parse_args()

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

    api_key = os.getenv("GEMINI_API_KEY")

    if not api_key:
        print("❌ Error: GEMINI_API_KEY environment variable not set.")
        print("   Option 1 - Create a .env file in your current folder with:")
        print("              GEMINI_API_KEY=your-api-key")
        print()
        print("   Option 2 - Set it in your terminal:")
        print("              PowerShell:       $env:GEMINI_API_KEY='your-api-key'")
        print("              Command Prompt:   set GEMINI_API_KEY=your-api-key")
        print("              Linux/Mac:        export GEMINI_API_KEY=your-api-key")
        sys.exit(1)

    try:
        if args.command == "list-personas":
            ai = Dracula(api_key=api_key)
            personas = ai.list_personas()
            print("\n🎭 Available personas:")
            for persona in personas:
                print(f"   - {persona}")
            print()
            return

        if args.command == "stats":
            ai = Dracula(api_key=api_key)
            stats = ai.get_stats()
            print("\n📊 Dracula Usage Stats:")
            print(f"   Total messages sent:         {stats['total_messages']}")
            print(f"   Total responses received:    {stats['total_responses']}")
            print(f"   Total characters sent:       {stats['total_characters_sent']}")
            print(
                f"   Total characters received:   {stats['total_characters_received']}"
            )
            print()
            return

        if args.command == "clear-stats":
            ai = Dracula(api_key=api_key)
            ai.reset_stats()
            print("✅ Stats have been reset.")
            return

        if args.command == "chat":
            ai = Dracula(
                api_key=api_key, language=args.language, temperature=args.temperature
            )

            if args.persona:
                ai.set_persona(args.persona)

            print()
            if args.stream:
                for chunk in ai.stream(args.message):
                    print(chunk, end="", flush=True)
                print("\n")
            else:
                response = ai.chat(args.message)
                print(f"🤖 {response}\n")

    except DraculaException as e:
        print(f"❌ Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
