"""Management script for creating organizations, projects, and API keys."""
import sys
import secrets
import uuid
from typing import Optional, Tuple, Dict
from api.utils import hash_api_key
from api.firestore_db import (
    create_organization as fs_create_organization,
    create_project as fs_create_project,
    create_api_key as fs_create_api_key
)


def create_organization(db, name: str) -> Dict:
    """Create a new organization (db parameter kept for compatibility but uses Firestore)."""
    org_data = {
        'id': str(uuid.uuid4()),
        'name': name,
        'plan': 'free',
        'subscription_status': 'inactive'
    }
    return fs_create_organization(org_data)


def create_project(db, organization_id: str, name: str) -> Dict:
    """Create a new project (db parameter kept for compatibility but uses Firestore)."""
    project_data = {
        'id': str(uuid.uuid4()),
        'organization_id': organization_id,
        'name': name,
        'policy_version': 1
    }
    return fs_create_project(project_data)


def create_api_key(
    db,
    organization_id: str,
    project_id: Optional[str],
    name: str,
    rate_limit: int = 100
) -> Tuple[Dict, str]:
    """Create a new API key and return the key object and the plaintext key (db parameter kept for compatibility but uses Firestore)."""
    # Generate secure API key
    plaintext_key = f"verity_{secrets.token_urlsafe(32)}"
    key_hash = hash_api_key(plaintext_key)
    
    api_key_data = {
        'id': str(uuid.uuid4()),
        'key_hash': key_hash,
        'organization_id': organization_id,
        'project_id': project_id,
        'name': name,
        'rate_limit': rate_limit,
        'request_count': 0,
        'last_used': None,
        'revoked_at': None
    }
    api_key = fs_create_api_key(api_key_data)
    
    return api_key, plaintext_key


def main():
    """CLI for management operations."""
    if len(sys.argv) < 2:
        print("Usage:")
        print("  python -m api.manage create-org <name>")
        print("  python -m api.manage create-project <org_id> <name>")
        print("  python -m api.manage create-key <org_id> [project_id] <name> [rate_limit]")
        sys.exit(1)
    
    # Firestore is initialized automatically, no need for init_db()
    db = None  # Kept for compatibility but not used
    
    try:
        command = sys.argv[1]
        
        if command == "create-org":
            if len(sys.argv) < 3:
                print("Error: organization name required")
                sys.exit(1)
            org = create_organization(db, sys.argv[2])
            print(f"Created organization:")
            print(f"  ID: {org.get('id')}")
            print(f"  Name: {org.get('name')}")
        
        elif command == "create-project":
            if len(sys.argv) < 4:
                print("Error: organization_id and project name required")
                sys.exit(1)
            project = create_project(db, sys.argv[2], sys.argv[3])
            print(f"Created project:")
            print(f"  ID: {project.get('id')}")
            print(f"  Name: {project.get('name')}")
            print(f"  Organization: {project.get('organization_id')}")
        
        elif command == "create-key":
            if len(sys.argv) < 4:
                print("Error: organization_id and key name required")
                print("Usage: create-key <org_id> [project_id] <name> [rate_limit]")
                sys.exit(1)
            org_id = sys.argv[2]
            # Check if 3rd arg is a UUID (project_id) or name
            project_id = None
            name = sys.argv[3]
            rate_limit = 100
            
            # If 4th arg exists and looks like a UUID, it's project_id
            if len(sys.argv) > 4:
                if len(sys.argv[4]) == 36 and sys.argv[4].count('-') == 4:
                    # Looks like a UUID, treat as project_id
                    project_id = sys.argv[4]
                    name = sys.argv[5] if len(sys.argv) > 5 else name
                    rate_limit = int(sys.argv[6]) if len(sys.argv) > 6 else 100
                else:
                    # Not a UUID, treat as name
                    name = sys.argv[4]
                    rate_limit = int(sys.argv[5]) if len(sys.argv) > 5 else 100
            
            api_key_obj, plaintext_key = create_api_key(db, org_id, project_id, name, rate_limit)
            print(f"Created API key:")
            print(f"  ID: {api_key_obj.get('id')}")
            print(f"  Name: {api_key_obj.get('name')}")
            print(f"  Organization: {api_key_obj.get('organization_id')}")
            print(f"  Project: {api_key_obj.get('project_id') or '(org-wide)'}")
            print(f"  Rate limit: {api_key_obj.get('rate_limit')}/hour")
            print(f"\n⚠️  SECRET KEY (save this - it won't be shown again):")
            print(f"  {plaintext_key}")
        
        else:
            print(f"Unknown command: {command}")
            sys.exit(1)
    
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()

