File size: 3,450 Bytes
5463318
9a10d7c
5463318
9a10d7c
5463318
 
 
 
 
 
 
 
 
 
 
38ee1b6
 
 
5463318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ee1b6
5463318
38ee1b6
 
5463318
 
 
 
 
 
38ee1b6
9a10d7c
 
 
 
 
 
 
 
 
 
 
 
 
 
38ee1b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5463318
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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('/<path:path>')
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)