#!/usr/bin/env python3
"""CLI script to generate API keys for DSOL.

Usage:
    uv run python scripts/create_api_key.py --name "My API Key"
    uv run python scripts/create_api_key.py --name "Limited Key" --rate-limit 30
"""

import argparse
import asyncio
import secrets
import sys
from pathlib import Path

# Add project root to path for imports
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.db.models import ApiKey
from src.db.session import async_session_maker
from src.services.auth_service import hash_api_key


async def create_api_key(
    name: str | None = None,
    rate_limit: int = 60,
) -> tuple[str, ApiKey]:
    """Create a new API key and store it in the database.

    Args:
        name: Optional name/description for the API key.
        rate_limit: Requests per minute limit (default: 60).

    Returns:
        Tuple of (plaintext_key, api_key_model).
    """
    # Generate secure random key (32 bytes = 64 hex chars)
    plaintext_key = secrets.token_hex(32)

    # Hash the key for storage
    key_hash = hash_api_key(plaintext_key)

    # Create database record
    async with async_session_maker() as session:
        api_key = ApiKey(
            key_hash=key_hash,
            name=name,
            rate_limit_per_minute=rate_limit,
            is_active=True,
        )
        session.add(api_key)
        await session.commit()
        await session.refresh(api_key)

    return plaintext_key, api_key


async def main() -> None:
    """Main entry point for the script."""
    parser = argparse.ArgumentParser(
        description="Generate a new API key for DSOL",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
    %(prog)s --name "Production API Key"
    %(prog)s --name "Test Key" --rate-limit 100
    %(prog)s  # Creates unnamed key with default rate limit
        """,
    )
    parser.add_argument(
        "--name",
        "-n",
        type=str,
        default=None,
        help="Optional name/description for the API key",
    )
    parser.add_argument(
        "--rate-limit",
        "-r",
        type=int,
        default=60,
        help="Rate limit (requests per minute), default: 60",
    )

    args = parser.parse_args()

    print("\n" + "=" * 60)
    print("DSOL API Key Generator")
    print("=" * 60)

    try:
        plaintext_key, api_key = await create_api_key(
            name=args.name,
            rate_limit=args.rate_limit,
        )

        print(f"\n✅ API Key created successfully!\n")
        print(f"ID:         {api_key.id}")
        print(f"Name:       {api_key.name or '(unnamed)'}")
        print(f"Rate Limit: {api_key.rate_limit_per_minute} req/min")
        print(f"Created:    {api_key.created_at}")
        print()
        print("=" * 60)
        print("⚠️  IMPORTANT: Save this key now! It will NOT be shown again.")
        print("=" * 60)
        print(f"\nAPI Key: {plaintext_key}\n")
        print("=" * 60)
        print("\nUsage:")
        print(f'  curl -H "X-API-Key: {plaintext_key}" http://localhost:8000/health')
        print()

    except Exception as e:
        print(f"\n❌ Error creating API key: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
