"""
Simple Client & API Key Management
As per requirement: ID, Name, Key only
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy.orm import Session
from src.database.connection import get_db, engine
from src.database.api_key_models import APIClient, AllowedDomain, Base
from datetime import datetime
import argparse

# Create tables
Base.metadata.create_all(bind=engine)


def create_client(
    client_id: str,
    client_name: str,
    domains: list = None,
    billing_plan: str = "internal",
    monthly_limit: int = None,
    billing_email: str = None
):
    """
    Create new API client with API key
    Simple: ID, Name, Key + optional domains
    """
    db = next(get_db())
    
    # Check if client_id already exists
    existing = db.query(APIClient).filter(APIClient.client_id == client_id).first()
    if existing:
        print(f"❌ Client ID '{client_id}' already exists")
        return
    
    # Generate API key
    api_key = APIClient.generate_api_key(client_id)
    api_key_hash = APIClient.hash_key(api_key)
    
    # Create client
    client = APIClient(
        client_id=client_id,
        client_name=client_name,
        api_key=api_key_hash,
        billing_plan=billing_plan,
        monthly_request_limit=monthly_limit,
        billing_email=billing_email
    )
    
    db.add(client)
    db.commit()
    
    # Add domains if provided
    if domains:
        for domain in domains:
            allowed_domain = AllowedDomain(
                domain=domain,
                client_id=client_id,
                description=f"Initial domain for {client_name}"
            )
            db.add(allowed_domain)
        db.commit()
    
    # Display success
    print("\n" + "="*80)
    print("✅ API CLIENT CREATED SUCCESSFULLY")
    print("="*80)
    print(f"Client ID:       {client_id}")
    print(f"Client Name:     {client_name}")
    print(f"Billing Plan:    {billing_plan}")
    if monthly_limit:
        print(f"Monthly Limit:   {monthly_limit:,} requests")
    if billing_email:
        print(f"Billing Email:   {billing_email}")
    print("="*80)
    print(f"\n🔑 API KEY (save this securely):")
    print(f"\n{api_key}\n")
    print("="*80)
    if domains:
        print(f"\n📋 Allowed Domains ({len(domains)}):")
        for domain in domains:
            print(f"   ✓ {domain}")
    print("="*80)
    print("\n⚠️  IMPORTANT: This is the ONLY time you'll see the full API key!")
    print("="*80 + "\n")


def add_domain(client_id: str, domain: str, description: str = ""):
    """Add domain to client's allowed list"""
    db = next(get_db())
    
    # Check if client exists
    client = db.query(APIClient).filter(APIClient.client_id == client_id).first()
    if not client:
        print(f"❌ Client '{client_id}' not found")
        return
    
    # Check if domain already exists
    existing = db.query(AllowedDomain).filter(
        AllowedDomain.domain == domain
    ).first()
    
    if existing:
        print(f"⚠️  Domain '{domain}' already exists")
        return
    
    # Add domain
    allowed_domain = AllowedDomain(
        domain=domain,
        client_id=client_id,
        description=description or f"Added for {client.client_name}"
    )
    
    db.add(allowed_domain)
    db.commit()
    
    print(f"✅ Domain '{domain}' added to client '{client_id}'")


def list_clients():
    """List all clients"""
    db = next(get_db())
    clients = db.query(APIClient).all()
    
    print("\n" + "="*80)
    print(f"📋 API CLIENTS ({len(clients)} total)")
    print("="*80)
    
    for client in clients:
        status = "✅ Active" if client.is_active else "❌ Inactive"
        
        # Get domains for this client
        domains = db.query(AllowedDomain).filter(
            AllowedDomain.client_id == client.client_id,
            AllowedDomain.is_active == True
        ).all()
        
        print(f"\nClient ID:     {client.client_id}")
        print(f"Name:          {client.client_name}")
        print(f"Status:        {status}")
        print(f"Plan:          {client.billing_plan}")
        print(f"Usage:         {client.total_requests:,} requests")
        print(f"Created:       {client.created_at}")
        print(f"Last Used:     {client.last_used_at or 'Never'}")
        
        if client.monthly_request_limit:
            print(f"Monthly Limit: {client.monthly_request_limit:,}")
        
        if domains:
            print(f"Domains ({len(domains)}):")
            for domain in domains:
                auto = " (auto)" if domain.auto_registered else ""
                print(f"   • {domain.domain}{auto}")
        
        print("-" * 80)


def list_domains():
    """List all allowed domains"""
    db = next(get_db())
    domains = db.query(AllowedDomain).filter(AllowedDomain.is_active == True).all()
    
    print("\n" + "="*80)
    print(f"🌐 ALLOWED DOMAINS ({len(domains)} total)")
    print("="*80)
    
    for domain in domains:
        auto = "🤖 Auto-registered" if domain.auto_registered else "✏️  Manual"
        print(f"\n{domain.domain}")
        print(f"   Client:      {domain.client_id}")
        print(f"   Type:        {auto}")
        print(f"   Requests:    {domain.total_requests:,}")
        print(f"   First seen:  {domain.first_seen_at}")
        print(f"   Last seen:   {domain.last_seen_at}")


def deactivate_client(client_id: str):
    """Deactivate a client"""
    db = next(get_db())
    client = db.query(APIClient).filter(APIClient.client_id == client_id).first()
    
    if not client:
        print(f"❌ Client '{client_id}' not found")
        return
    
    client.is_active = False
    db.commit()
    
    print(f"✅ Client '{client_id}' has been deactivated")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Manage API Clients")
    subparsers = parser.add_subparsers(dest="command")
    
    # Create client
    create_parser = subparsers.add_parser("create", help="Create new API client")
    create_parser.add_argument("--id", required=True, help="Client ID (e.g., myrx-web)")
    create_parser.add_argument("--name", required=True, help="Client name (e.g., MyRx Web App)")
    create_parser.add_argument("--domains", nargs="+", help="Allowed domains")
    create_parser.add_argument("--plan", default="internal", help="Billing plan")
    create_parser.add_argument("--limit", type=int, help="Monthly request limit")
    create_parser.add_argument("--email", help="Billing email")
    
    # Add domain
    domain_parser = subparsers.add_parser("add-domain", help="Add domain to client")
    domain_parser.add_argument("--client", required=True, help="Client ID")
    domain_parser.add_argument("--domain", required=True, help="Domain URL")
    domain_parser.add_argument("--description", default="", help="Description")
    
    # List clients
    list_parser = subparsers.add_parser("list", help="List all clients")
    
    # List domains
    domains_parser = subparsers.add_parser("domains", help="List all allowed domains")
    
    # Deactivate
    deactivate_parser = subparsers.add_parser("deactivate", help="Deactivate a client")
    deactivate_parser.add_argument("client_id", help="Client ID to deactivate")
    
    args = parser.parse_args()
    
    if args.command == "create":
        create_client(
            client_id=args.id,
            client_name=args.name,
            domains=args.domains,
            billing_plan=args.plan,
            monthly_limit=args.limit,
            billing_email=args.email
        )
    elif args.command == "add-domain":
        add_domain(args.client, args.domain, args.description)
    elif args.command == "list":
        list_clients()
    elif args.command == "domains":
        list_domains()
    elif args.command == "deactivate":
        deactivate_client(args.client_id)
    else:
        parser.print_help()
