"""
Main Flask Application - Modular API
All routes are defined in the routes/ directory as blueprints
"""
import os
from flask import Flask, send_from_directory
from flask_cors import CORS
from config import db

app = Flask(__name__)
app.config['SECRET_KEY'] = 'MySecret'  # Use env variable in production
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB max

# Database Configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:@localhost/ashlya_ashlya_academy_new'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize SQLAlchemy
db.init_app(app)

# Enable CORS
CORS(app)

# ==========================================
# REGISTER MODULAR BLUEPRINTS
# ==========================================
from routes.auth import auth_bp
from routes.admin_routes import admin_bp
from routes.institute_routes import institute_bp
from routes.superadmin_routes import superadmin_bp
from routes.jaas_webhook import jaas_webhook_bp
from routes.template_admin_routes import template_admin_bp
from routes.extended_admin_routes import extended_admin_bp
from routes.model_routes import model_bp
from routes.token_routes import token_bp
from routes.slider_routes import slider_bp
from routes.subscription_routes import subscription_bp
from routes.analytics_routes import analytics_bp
from routes.ai_routes import ai_bp

app.register_blueprint(auth_bp)           # Auth: /api/login, /api/logout, /api/me
app.register_blueprint(admin_bp)          # Content: /api/users, /api/courses, /api/videos, /api/topics
app.register_blueprint(institute_bp)      # Institute: /api/institute/*
app.register_blueprint(superadmin_bp)     # Super Admin: /api/admin/*
app.register_blueprint(jaas_webhook_bp, url_prefix='/api')  # JaaS Webhooks: /api/jaas/webhook
app.register_blueprint(template_admin_bp) # Template Admin: /api/admin/institute/*/config, widgets
app.register_blueprint(extended_admin_bp) # Extended: /api/coupons, /api/payments, /api/institute/reviews, etc.
app.register_blueprint(model_bp)          # AI Models: /api/models
app.register_blueprint(token_bp)          # Tokens: /api/tokens
app.register_blueprint(slider_bp)         # Sliders: /api/admin/sliders
app.register_blueprint(subscription_bp)   # Subscriptions: /api/admin/subscriptions
app.register_blueprint(analytics_bp)      # Analytics & Reports: /api/dashboard/stats, /api/analytics/*
app.register_blueprint(ai_bp)             # AI Assistant: /api/ai/generate, /api/ai/fill-form

# ==========================================
# STATIC FILES
# ==========================================
@app.route('/static/uploads/<path:filename>')
def serve_uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/uploads/recordings/<filename>')
def serve_recording_file(filename):
    """Serve recorded live class videos"""
    recordings_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'recordings')
    return send_from_directory(recordings_dir, filename)


# ==========================================
# LEGACY ROUTES (to be migrated)
# ==========================================
# These routes will be moved to blueprints incrementally

from add_course import add_courses_page
from add_video import get_video_duration
from quiz import get_quiz_details
from topicDetail import get_topic_detail
from videoDetail import get_video_detail
from courseDetail import get_course_detail
from userdetail import get_user_detail
from functools import wraps
from flask import request, jsonify
import jwt
from werkzeug.security import generate_password_hash
from models.user import Admin, Courses, Category, Instructor, User, Topic
from models.videoandrecent import Video
from models.quiz import Questions, Options

SUPERADMIN_EMAIL = "regmibishal964@gmail.com"

def token_required_legacy(f):
    """Legacy token decorator for routes not yet migrated"""
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('x-access-token')
        if not token:
            return jsonify({'message': 'Token is missing!'}), 401
        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
            user_role = data.get('role')
            public_id = data['public_id']
            if public_id == 'superadmin' and user_role == 'superadmin':
                current_user = Admin(public_id='superadmin', name='Super Admin', email=SUPERADMIN_EMAIL, role='superadmin')
            else:
                current_user = Admin.query.filter_by(public_id=public_id).first()
            if not current_user:
                return jsonify({'message': 'User not found!'}), 401
        except jwt.ExpiredSignatureError:
            return jsonify({'message': 'Token has expired!'}), 401
        except jwt.InvalidTokenError:
            return jsonify({'message': 'Token is invalid!'}), 401
        except Exception as e:
            return jsonify({'message': f'Token error: {str(e)}'}), 401
        return f(current_user, user_role, *args, **kwargs)
    return decorated


@app.route('/api/get-question', methods=['POST'])
@token_required_legacy
def get_question(current_user, user_role):
    import urllib.parse as urlparse
    data = request.json
    question_text = urlparse.unquote(data.get('question_text'))
    question = Questions.query.filter_by(question_id=question_text).first()
    if not question:
        return jsonify({"message": "Question not found!"}), 404
    options = Options.query.filter_by(question_id=question.question_id).all()
    options_list = [{"option_id": opt.option_id, "question_id": opt.question_id, "option_text": opt.option_text, "is_correct": opt.is_correct} for opt in options]
    return jsonify({"question_id": question.question_id, "question_text": question.question_text, "options": options_list}), 200


@app.route('/api/get_user_detail', methods=['POST'])
@token_required_legacy
def get_user_det(current_user, user_role):
    return get_user_detail(request, User)


@app.route('/api/get_course_detail', methods=['POST'])
@token_required_legacy
def get_course_det(current_user, user_role):
    return get_course_detail(request, Courses)


@app.route('/api/get_video_detail', methods=['POST'])
@token_required_legacy
def get_video_det(current_user, user_role):
    return get_video_detail(request, Video)


@app.route('/api/get_topic_detail', methods=['POST'])
@token_required_legacy
def get_topic_det(current_user, user_role):
    return get_topic_detail(request, Topic, Video)




if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=30015)
