import click
from flask.cli import with_appcontext
from app.extensions import db
from app.models import User
import logging

logging.basicConfig(filename='/home/itinysaq/lkgetaways.com/commands.log', level=logging.DEBUG)
logger = logging.getLogger(__name__)

@click.command('create-admin')
@click.option('--username', prompt='Enter admin username', help='The username of the admin user')
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='The password of the admin user')
@with_appcontext
def create_admin(username, password):
    user = User.query.filter_by(username=username).first()
    if user:
        click.echo(f"User {username} already exists.")
        return
    
    new_user = User(username=username)
    new_user.set_password(password)
    db.session.add(new_user)
    db.session.commit()
    click.echo(f"Admin user {username} created successfully.")

@click.command('init-db')
@with_appcontext
def init_db():
    db.create_all()
    click.echo("Database tables created.")

@click.command('empty-db')
@with_appcontext
def empty_db():
    logger.debug("empty-db command called")
    if click.confirm('Are you sure you want to empty the database? This action cannot be undone.', abort=True):
        try:
            # Disable foreign key checks
            db.session.execute('PRAGMA foreign_keys = OFF;')
            
            # Drop all tables
            db.drop_all()
            
            # Recreate all tables
            db.create_all()
            
            # Re-enable foreign key checks
            db.session.execute('PRAGMA foreign_keys = ON;')
            
            db.session.commit()
            click.echo('Database emptied successfully.')
            logger.debug("Database emptied successfully")
        except Exception as e:
            db.session.rollback()
            error_msg = f'An error occurred: {str(e)}'
            click.echo(error_msg)
            logger.error(error_msg)
        finally:
            db.session.close()

def init_app(app):
    app.cli.add_command(create_admin)
    app.cli.add_command(init_db)
    app.cli.add_command(empty_db)
    logger.debug("All commands registered")