import click
import uvicorn
import asyncio
from cpm_assessment.config import get_settings
from cpm_assessment.models import User, UserCreate
from motor.motor_asyncio import AsyncIOMotorClient
import bcrypt

@click.group()
def main():
    """CPM Assessment CLI Tool."""
    pass

@main.command()
@click.option('--host', default='127.0.0.1', help='The interface to bind to.')
@click.option('--port', default=8000, type=int, help='The port to bind to.')
@click.option('--reload/--no-reload', default=False, help='Enable auto-reload.')
def run(host, port, reload):
    """Run the FastAPI application."""
    print(f"Starting server on {host}:{port}")
    uvicorn.run("cpm_assessment.app:create_app", host=host, port=port, reload=reload, factory=True)

async def seed_db():
    settings = get_settings()
    client = AsyncIOMotorClient(settings.MONGO_URL)
    db = client[settings.DB_NAME]
    
    # Check if admin user exists
    existing_admin = await db.users.find_one({"email": "admin@vrwellness.in"})
    if existing_admin:
        print("Admin user already exists. Skipping seed.")
        return

    # Create admin user
    hashed_password = bcrypt.hashpw('Askme123'.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
    admin_user = UserCreate(
        username='admin',
        email='admin@vrwellness.in',
        password=hashed_password,
        role='admin',
        full_name="Administrator"
    )
    
    user_doc = admin_user.model_dump()
    # Note: In real app, password should be hashed before storing if model stores plain text
    # But UserCreate has password field. We should store hashed password.
    # Let's adjust logic:
    # We should store hashed password in db, not plain text from UserCreate.
    # The User model (schema) doesn't have password field (it's in UserCreate).
    # We need a UserInDB model or just store the dict.
    
    user_doc['password'] = hashed_password # Overwrite plain password
    user_doc['created_at'] = user_doc.get('created_at', None) # Ensure datetime is handled if needed
    
    # Insert
    await db.users.insert_one(user_doc)
    print("Admin user created successfully.")

@main.command("seed")
def seed_command():
    """Seeds the database with an initial admin user."""
    asyncio.run(seed_db())

if __name__ == '__main__':
    main()
