from flask import Flask, session, redirect, url_for
import secrets
import os

# Get the directory where this script is located
basedir = os.path.abspath(os.path.dirname(__file__))

# Initialize Flask with explicit paths
app = Flask(__name__,
            template_folder=os.path.join(basedir, 'templates'),
            static_folder=os.path.join(basedir, 'static'))

# Configure session - generate a random secret key
app.secret_key = secrets.token_hex(32)
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'

# Import and register blueprints
from blueprints.auth import auth_bp
from blueprints.users import users_bp
from blueprints.products import products_bp
from blueprints.canvas import canvas_bp

app.register_blueprint(auth_bp)
app.register_blueprint(users_bp)
app.register_blueprint(products_bp)
app.register_blueprint(canvas_bp)

# Comment Change
# Home route
@app.route('/')
def home():
    """Redirect to login if not authenticated, otherwise show home"""
    if 'user_id' not in session:
        return redirect(url_for('auth.login_page'))
    
    # If user hasn't selected a location yet, redirect to selection
    if not session.get('currentLocation') and len(session.get('accessibleLocations', [])) > 1:
        return redirect(url_for('auth.select_location_page'))
    
    return f"""
    <html>
    <head><title>Home</title></head>
    <body style="font-family: Arial; padding: 20px;">
        <h1>Welcome, {session.get('username', 'User')}!</h1>
        <p>Current Location: {session.get('currentLocation', 'Not selected')}</p>
        <ul>
            <li><a href="{url_for('products.product_finder')}">🔍 Product Finder Quiz</a></li>
            <li><a href="{url_for('products.product_manager')}">📦 Manage Products</a></li>
            <li><a href="{url_for('users.user_manager')}">👥 Manage Users</a></li>
            <li><a href="{url_for('auth.select_location_page')}">📍 Change Location</a></li>
            <li><a href="{url_for('auth.logout')}">🚪 Logout</a></li>
        </ul>
    </body>
    </html>
    """

@app.route('/test')
def test():
    """Test route to verify app is running"""
    import sys
    return f"""
    <html>
    <head><title>Test Page</title></head>
    <body style="font-family: Arial; padding: 20px;">
        <h1>Flask App is Running!</h1>
        <ul>
            <li><strong>Python:</strong> {sys.version}</li>
            <li><strong>Routes:</strong> {len(list(app.url_map.iter_rules()))}</li>
        </ul>
        <p><a href="{url_for('auth.login_page')}">Login</a></p>
    </body>
    </html>
    """

# Error handlers
@app.errorhandler(404)
def page_not_found(e):
    return "<h1>404 - Page Not Found</h1>", 404

@app.errorhandler(500)
def internal_error(e):
    return "<h1>500 - Internal Server Error</h1>", 500

# This is the critical line for Passenger
application = app

if __name__ == '__main__':
    # Create necessary directories
    os.makedirs(os.path.join(basedir, 'templates'), exist_ok=True)
    os.makedirs(os.path.join(basedir, 'data'), exist_ok=True)
    
    # Run the application
    app.run(debug=True, host='0.0.0.0', port=8080)   