import argparse
import os
import sys
from dotenv import load_dotenv

from .client import Dracula
from .exceptions import DraculaException
from .logger import get_logger
from ._version import __version__

logger = get_logger("dracula.cli")


def main():
    load_dotenv()

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

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

    subparsers = parser.add_subparsers(dest="command", help="Available 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 in real-time"
    )

    subparsers.add_parser("list-personas", help="List all available personas")
    subparsers.add_parser("stats", help="Show usage statistics")
    subparsers.add_parser("clear-stats", help="Reset usage statistics")
    subparsers.add_parser("ui", help="Launch the Dracula Desktop Interface")
    args = parser.parse_args()

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

    api_key = os.getenv("GEMINI_API_KEY")

    if not api_key:
        print("❌ Error: GEMINI_API_KEY environment variable not found.")
        print("\n🔒 Security Best Practice:")
        print(
            "   Create a .env file in your project directory with the following content:"
        )
        print("   GEMINI_API_KEY=your-actual-api-key")
        print("\n   Alternatively, set it directly in your terminal:")
        print("   Linux/macOS: export GEMINI_API_KEY='your-key'")
        print("   Windows CMD: set GEMINI_API_KEY=your-key")
        print("   PowerShell:  $env:GEMINI_API_KEY='your-key'")
        sys.exit(1)

    try:
        if args.command in ["list-personas", "stats", "clear-stats", "chat", "ui"]:
            ai = Dracula(api_key=api_key)

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

        if args.command == "stats":
            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.reset_stats()
            print("✅ Stats have been successfully reset.")
            return

        if args.command == "ui":
            try:
                from dracula.ui import launch

                print("🧛 Launching Dracula Desktop UI...")
                launch(ai)
            except ImportError:
                print("\n❌ Error: UI dependencies are not installed.")
                print("   The desktop interface requires additional packages.")
                print("   Please install them using: pip install dracula-ai[ui]\n")
                sys.exit(1)
            return

        if args.command == "chat":
            ai.language = args.language
            ai.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:
        logger.error(f"CLI encountered an error: {str(e)}")
        print(f"\n❌ Dracula Error: {e}\n")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n\n🛑 Operation cancelled by user.")
        sys.exit(0)


if __name__ == "__main__":
    main()
