import os
import sys
from datetime import timedelta

# Add the src directory to the Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from flask import Flask, send_from_directory, session, request
from flask_cors import CORS
from models.user_email import db
from models.inspection import Inspection
from routes.auth_email import auth_bp
from routes.rooms import rooms_bp

def create_app():
    app = Flask(__name__, static_folder='static', static_url_path='')
    
    # Configuration
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')
    
    # SQLite Database Configuration for testing
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///property_inspection.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # Session configuration
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
    app.config['SESSION_COOKIE_SECURE'] = False  # Set to True in production with HTTPS
    app.config['SESSION_COOKIE_HTTPONLY'] = True
    app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
    
    # Initialize extensions
    db.init_app(app)
    CORS(app, supports_credentials=True, origins=['*'])
    
    # Register blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(rooms_bp)
    
    # Create tables
    with app.app_context():
        try:
            db.create_all()
            print("Database tables created successfully!")
        except Exception as e:
            print(f"Error creating database tables: {e}")
    
    @app.before_request
    def make_session_permanent():
        session.permanent = True
    
    @app.route('/')
    def serve_index():
        """Serve the React app"""
        try:
            return send_from_directory(app.static_folder, 'index.html')
        except FileNotFoundError:
            return "index.html not found", 404
    
    @app.route('/<path:path>')
    def serve_static(path):
        """Serve static files or fallback to index.html for React routing"""
        # Don't intercept API routes
        if path.startswith('api/'):
            return "API endpoint not found", 404
            
        try:
            return send_from_directory(app.static_folder, path)
        except FileNotFoundError:
            # Fallback to index.html for React routing
            try:
                return send_from_directory(app.static_folder, 'index.html')
            except FileNotFoundError:
                return "index.html not found", 404
    
    @app.errorhandler(404)
    def not_found(error):
        """Handle 404 errors by serving index.html for React routing"""
        try:
            return send_from_directory(app.static_folder, 'index.html')
        except FileNotFoundError:
            return "index.html not found", 404
    
    return app

app = create_app()

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

