import os import json import logging from flask import Flask, jsonify, request, send_from_directory, Response from flask_cors import CORS from dotenv import load_dotenv # Import Blueprints from routes.profile import profile_bp from routes.generate import generate_bp from routes.dashboard import dashboard_bp # Load environment variables load_dotenv(dotenv_path='.env.local') FRONTEND_DIST_DIR = os.path.join(os.path.dirname(__file__), "frontend_dist") app = Flask(__name__, static_folder=None) # Configure CORS - Enable proper preflight headers CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True) # Register Blueprints app.register_blueprint(profile_bp) app.register_blueprint(generate_bp) app.register_blueprint(dashboard_bp) # Global configuration app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB # ----------------------------------------------------------------------------- # Global Error Handling # ----------------------------------------------------------------------------- @app.errorhandler(404) def resource_not_found(e): return jsonify(error=str(e)), 404 @app.errorhandler(500) def internal_server_error(e): app.logger.error(f"Server Error: {e}") return jsonify(error="An unexpected internal server error occurred."), 500 @app.errorhandler(Exception) def handle_exception(e): """Handle all other unhandled exceptions.""" app.logger.error(f"Unhandled Exception: {e}") # If the exception has a status code (e.g. from Werkzeug), use it code = 500 if hasattr(e, 'code'): code = e.code return jsonify(error=str(e)), code # ----------------------------------------------------------------------------- # Home Route / SPA serving # ----------------------------------------------------------------------------- @app.route('/api/health') def health(): return jsonify({ "status": "online", "message": "ExamCraft Backend API is running", "version": "1.1.0" }) @app.route('/config.js') def config_js(): supabase_url = os.getenv('VITE_SUPABASE_URL') or os.getenv('SUPABASE_URL') or '' supabase_anon = os.getenv('VITE_SUPABASE_ANON_KEY') or os.getenv('SUPABASE_ANON_KEY') or '' api_url = os.getenv('VITE_API_URL') or '' payload = { "VITE_SUPABASE_URL": supabase_url, "VITE_SUPABASE_ANON_KEY": supabase_anon, "VITE_API_URL": api_url, } js = f"window.__APP_CONFIG__ = {json.dumps(payload)};" return Response(js, mimetype='application/javascript') @app.route('/', defaults={'path': ''}) @app.route('/') def serve_frontend(path): if path.startswith(('api/', 'upload', 'generate', 'download', 'regenerate-question')): return jsonify({"error": "Not found"}), 404 requested_path = os.path.join(FRONTEND_DIST_DIR, path) if path and os.path.isfile(requested_path): return send_from_directory(FRONTEND_DIST_DIR, path) index_path = os.path.join(FRONTEND_DIST_DIR, 'index.html') if os.path.exists(index_path): return send_from_directory(FRONTEND_DIST_DIR, 'index.html') return jsonify({ "status": "online", "message": "Frontend build is not available", "version": "1.1.0" }), 503 if __name__ == '__main__': # Ensure uploads directory exists os.makedirs('uploads', exist_ok=True) import os port = int(os.environ.get('PORT', 7860)) app.run(host='0.0.0.0', port=port, debug=True)