from sys import prefix
from flask import Flask, send_from_directory
# from FreeBug.backend.blueprints import notification
from db.model import db
from config import *
from db.model import User
from werkzeug.security import generate_password_hash
from sqlalchemy import text
from flask import jsonify
import uuid
from datetime import datetime
from constants import UserRole
from utils.utils import random_string_generator, hash_string
from flask_cors import CORS


from blueprints.profile import profile as profileBlueprint
from blueprints.session import session as sessionBlueprint
from blueprints.admin import admin as adminBlueprint
from blueprints.chat import chat as chatBlueprint
from blueprints.public import public_summary as publicBlueprint
from blueprints.course import course as courseBlueprint
from blueprints.badge import badge_route as badgeBlueprint
from blueprints.quiz import quiz as quizBlueprint

app = Flask(__name__)

# Enable CORS for all routes
CORS(app)
# Enable CORS for specific routes
# CORS(app, resources={
#     r"*": {"origins": "*"}  # Allows CORS for all `/api/` routes
# })
# Set configuration directly on the app instance
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif','pdf'}
app.config['MAX_CONTENT_LENGTH'] = 1600 * 1000 * 1000

app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI

db.init_app(app)

app.register_blueprint(profileBlueprint, url_prefix='/api/profile')
app.register_blueprint(sessionBlueprint,url_prefix='/api/session')
app.register_blueprint(adminBlueprint,url_prefix='/api/admin')
app.register_blueprint(badgeBlueprint, url_prefix='/api/badge')

# TODO: Register Notif API
app.register_blueprint(chatBlueprint,url_prefix='/api/chat')
app.register_blueprint(quizBlueprint,url_prefix='/api/quiz')
app.register_blueprint(publicBlueprint,url_prefix='/api/public')
app.register_blueprint(courseBlueprint,url_prefix='/api/course')

@app.route('/media/<string:filename>')
def send_file(filename):
    return send_from_directory(USER_UPLOADS_DIR, filename)

@app.route('/courseSegment/<string:filename>/<int:page>/<string:dtype>')
def get_pdf_file_as_pages(filename: str, page: int, dtype: str):
    if dtype == 'txt':
        return send_from_directory(os.path.join(USER_UPLOADS_DIR, filename+'_parts'), f"{page}.txt")
    else:
        return send_from_directory(os.path.join(USER_UPLOADS_DIR, filename+'_parts'), f"{page}.pdf")

@app.route('/', methods=['GET', 'POST'])
def homepage():
    return {'message': 'Welcome back !'}, 200

@app.route('/seedData', methods=['GET'])
def seed_data():
    try:
        # Drop and recreate schema (only for testing, not recommended in production)
        sql = text('DROP SCHEMA public CASCADE; CREATE SCHEMA public;')
        db.session.execute(sql)
        db.session.commit()
        db.create_all()  # Recreate tables

        # Define roles and constants (ensure UserRole.USER is an integer or map it)
        # Create seed users
        users = [ User(
                    email=f"user{i}@example.com",  firstName=f"FirstName{i}", lastName=f"LastName{i}",
                    username=f"username{i}", hash_password=generate_password_hash("password123"),
                    activationKey=hash_string(random_string_generator(16)), pfpFilename=DEFAULT_PROFILE_FILE,
                    joinedDate=datetime.utcnow(), lastOnline=datetime.utcnow(),
                    bio=f"This is user{i}'s bio.", role=int(UserRole.USER),
                    isActivated=True, sessions=[], user_badges=[],
                    enrollments=[], quizzes=[], quiz_attempts=[], chats=[], notifications=[],publications=[])
                for i in range(1, 6) ]
        db.session.add_all(users)
        db.session.commit()
        return {"message": "Users seeded successfully!"}, 201
    except Exception as e:
        db.session.rollback()
        return {"error": str(e)}, 500

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=9999, debug=True)