"""
Create MongoDB application user for PIF Compiler.

This script creates a dedicated user with readWrite permissions
on the toxinfo database instead of using the admin account.
"""

from pymongo import MongoClient
from pymongo.errors import DuplicateKeyError, OperationFailure
import sys


def create_app_user():
    """Create application user for toxinfo database."""

    # Configuration
    ADMIN_USER = "admin"
    ADMIN_PASSWORD = "admin123"
    MONGO_HOST = "localhost"
    MONGO_PORT = 27017

    APP_USER = "pif_app"
    APP_PASSWORD = "marox123"
    APP_DATABASE = "pif-projects"

    print(f"Connecting to MongoDB as admin...")

    try:
        # Connect as admin
        client = MongoClient(
            f"mongodb://{ADMIN_USER}:{ADMIN_PASSWORD}@{MONGO_HOST}:{MONGO_PORT}/?authSource=admin",
            serverSelectionTimeoutMS=5000
        )

        # Test connection
        client.admin.command('ping')
        print("✓ Connected to MongoDB successfully")

        # Switch to application database
        db = client[APP_DATABASE]

        # Create application user
        print(f"\nCreating user '{APP_USER}' with readWrite permissions on '{APP_DATABASE}'...")

        db.command(
            "createUser",
            APP_USER,
            pwd=APP_PASSWORD,
            roles=[{"role": "readWrite", "db": APP_DATABASE}]
        )

        print(f"✓ User '{APP_USER}' created successfully!")
        print(f"\nConnection details:")
        print(f"  Username: {APP_USER}")
        print(f"  Password: {APP_PASSWORD}")
        print(f"  Database: {APP_DATABASE}")
        print(f"  Connection String: mongodb://{APP_USER}:{APP_PASSWORD}@{MONGO_HOST}:{MONGO_PORT}/{APP_DATABASE}?authSource={APP_DATABASE}")

        print(f"\nUpdate your mongo_functions.py with:")
        print(f"  db = connect(user='{APP_USER}', password='{APP_PASSWORD}', database='{APP_DATABASE}')")

        client.close()
        return 0

    except DuplicateKeyError:
        print(f"⚠ User '{APP_USER}' already exists!")
        print(f"\nTo delete and recreate, run:")
        print(f"  docker exec -it pif_mongodb mongosh -u admin -p admin123 --authenticationDatabase admin")
        print(f"  use {APP_DATABASE}")
        print(f"  db.dropUser('{APP_USER}')")
        return 1

    except OperationFailure as e:
        print(f"✗ MongoDB operation failed: {e}")
        return 1

    except Exception as e:
        print(f"✗ Error: {e}")
        print("\nMake sure MongoDB is running:")
        print("  cd utils")
        print("  docker-compose up -d")
        return 1


if __name__ == "__main__":
    sys.exit(create_app_user())
