from flask import Flask, request, redirect, url_for, render_template, session
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from uuid import uuid4
import click

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = 'your_secret_key'
db = SQLAlchemy(app)
login_manager = LoginManager(app)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    referral_code = db.Column(db.String(36), unique=True, nullable=False)
    invited_by_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
    is_admin = db.Column(db.Boolean, default=False)
    invitees = db.relationship('User', backref=db.backref('inviter', remote_side=[id]))

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/register/<referral_code>', methods=['GET', 'POST'])
def register(referral_code):
    inviter = User.query.filter_by(referral_code=referral_code).first_or_404()
    if request.method == 'POST':
        username = request.form['username']
        new_user = User(username=username, referral_code=str(uuid4()), invited_by_id=inviter.id)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('login'))
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        user = User.query.filter_by(username=username).first()
        if user:
            login_user(user)
            return redirect(url_for('home'))
    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/remove_user/<int:user_id>')
@login_required
def remove_user(user_id):
    if not current_user.is_admin:
        return redirect(url_for('home'))
    user_to_remove = User.query.get_or_404(user_id)
    invitees = User.query.filter_by(invited_by_id=user_to_remove.id).all()
    for invitee in invitees:
        db.session.delete(invitee)
    db.session.delete(user_to_remove)
    db.session.commit()
    return redirect(url_for('admin_dashboard'))

@app.cli.command('remove_user')
@click.argument('username')
def remove_user_cli(username):
    user_to_remove = User.query.filter_by(username=username).first()
    if user_to_remove:
        invitees = User.query.filter_by(invited_by_id=user_to_remove.id).all()
        for invitee in invitees:
            db.session.delete(invitee)
        db.session.delete(user_to_remove)
        db.session.commit()
        print(f'User {username} and their invitees have been removed.')
    else:
        print(f'User {username} not found.')

@app.route('/home')
@login_required
def home():
    return "Home page"

@app.route('/admin_dashboard')
@login_required
def admin_dashboard():
    if not current_user.is_admin:
        return redirect(url_for('home'))
    users = User.query.all()
    return render_template('admin_dashboard.html', users=users)

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)
