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

# 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'] = config.SESSION_COOKIE_HTTPONLY
app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE

# Configure SQLAlchemy only if using database
if config.USE_DATABASE:
    app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = config.SQLALCHEMY_TRACK_MODIFICATIONS
    app.config['SQLALCHEMY_ECHO'] = config.SQLALCHEMY_ECHO
    
    # Initialize database
    from models import db
    db.init_app(app)

# 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

# Database initialization route
@app.route('/init-db')
def init_db():
    """Initialize the database (create all tables)"""
    if not config.USE_DATABASE:
        return """
        <html>
        <head><title>Database Not Enabled</title></head>
        <body style="font-family: Arial; padding: 20px;">
            <h1>⚠️ Database Not Enabled</h1>
            <p>The application is currently configured to use JSON files.</p>
            <p>Set USE_DATABASE = True in config.py to enable SQLite.</p>
            <p><a href="/">Go to Home</a></p>
        </body>
        </html>
        """
    
    try:
        from models import db
        with app.app_context():
            db.create_all()
        return """
        <html>
        <head><title>Database Initialized</title></head>
        <body style="font-family: Arial; padding: 20px;">
            <h1>✅ Database Initialized Successfully!</h1>
            <p>All tables have been created.</p>
            <p><a href="/">Go to Home</a></p>
        </body>
        </html>
        """
    except Exception as e:
        return f"""
        <html>
        <head><title>Database Error</title></head>
        <body style="font-family: Arial; padding: 20px;">
            <h1>❌ Database Initialization Failed</h1>
            <p>Error: {str(e)}</p>
        </body>
        </html>
        """, 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)   