# backend/app/cli.py

import click
from flask import Blueprint, current_app
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.security import generate_password_hash

# Import your database instance and models
from .extensions import db
from .models.user import User  # Assuming you have a User model

# Create a Blueprint for custom CLI commands
# This Blueprint will be registered in your app.py
commands_bp = Blueprint("commands", __name__)


@commands_bp.cli.command("init-db")
@click.option(
    "--drop-all", is_flag=True, help="Drop all existing tables before creating."
)
def init_db(drop_all):
    """
    Initializes the database schema.
    Creates all tables defined in your SQLAlchemy models.
    """
    if drop_all:
        try:
            db.drop_all()
            click.echo("Dropped all existing database tables.")
        except SQLAlchemyError as e:
            click.echo(f"Error dropping tables: {e}")
            return

    try:
        db.create_all()
        click.echo("Database tables created successfully.")
    except SQLAlchemyError as e:
        click.echo(f"Error creating tables: {e}")


@commands_bp.cli.command("seed-db")
@click.option("--users", default=5, type=int, help="Number of dummy users to create.")
def seed_db(users):
    """
    Seeds the database with initial data (e.g., dummy users, roles).
    """
    click.echo(f"Seeding database with {users} dummy users...")
    try:
        # Example: Create dummy users
        for i in range(1, users + 1):
            username = f"user{i}"
            email = f"user{i}@example.com"
            password_hash = generate_password_hash(
                "password123"
            )  # Hash a default password

            existing_user = db.session.scalar(db.select(User).filter_by(email=email))
            if existing_user:
                click.echo(f"User '{email}' already exists. Skipping.")
                continue

            user = User(
                username=username,
                email=email,
                password_hash=password_hash,
                is_admin=(i == 1),  # Make the first user an admin
            )
            db.session.add(user)
            click.echo(f"Added user: {username} ({email})")

        db.session.commit()
        click.echo("Database seeding complete.")
    except SQLAlchemyError as e:
        db.session.rollback()
        click.echo(f"Error seeding database: {e}")
    finally:
        db.session.close()  # Ensure the session is closed


@commands_bp.cli.command("create-admin")
@click.option("--username", prompt=True, help="The username for the admin.")
@click.option("--email", prompt=True, help="The email for the admin.")
@click.option(
    "--password",
    prompt=True,
    hide_input=True,
    confirmation_prompt=True,
    help="The password for the admin.",
)
def create_admin(username, email, password):
    """
    Creates a new administrator user.
    """
    try:
        existing_user = db.session.scalar(db.select(User).filter_by(email=email))
        if existing_user:
            click.echo(f"Error: User with email '{email}' already exists.", err=True)
            return

        password_hash = generate_password_hash(password)
        admin_user = User(
            username=username,
            email=email,
            password_hash=password_hash,
            is_admin=True,  # Mark as admin
        )
        db.session.add(admin_user)
        db.session.commit()
        click.echo(f"Administrator user '{username}' ({email}) created successfully.")
    except SQLAlchemyError as e:
        db.session.rollback()
        click.echo(f"Error creating admin user: {e}", err=True)
    finally:
        db.session.close()


# Add more commands as needed, e.g.:
# @commands_bp.cli.command('purge-old-data')
# @click.option('--days', default=90, type=int, help='Remove data older than X days.')
# def purge_old_data(days):
#     """Removes old, stale data from the database."""
#     click.echo(f"Purging data older than {days} days...")
#     # Implement your purging logic here
#     click.echo("Data purging complete.")
