from flask import Flask
from flask_cors import CORS
from app.core import socketio
from app.chat.routes import check_inactive_users  # just the function
from dotenv import load_dotenv
import os

# Load environment variables
load_dotenv()

def create_app():
    flask_app = Flask(__name__)
    flask_app.config["SECRET_KEY"] = os.getenv('FLASK_SECRET_KEY', 'your_secret_key_here')
    
    # Configure CORS
    CORS(flask_app, 
         resources={r"/*": {"origins": "http://localhost:3000"}},
         supports_credentials=True,
         allow_headers=["Content-Type", "Authorization", "Access-Control-Allow-Origin"],
         methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])

    @flask_app.after_request
    def add_cors_headers(response):
        response.headers["Access-Control-Allow-Origin"] = "http://localhost:3000"
        response.headers["Access-Control-Allow-Credentials"] = "true"
        response.headers["Access-Control-Allow-Headers"] = "Content-Type,Authorization,Access-Control-Allow-Origin"
        response.headers["Access-Control-Allow-Methods"] = "GET,PUT,POST,DELETE,OPTIONS"
        return response

    # SocketIO handlers
    import app.chat.routes    # registers @socketio handlers

    # HTTP APIs
    from app.character.routes       import character_bp
    from app.actions.routes   import action_bp
    from app.api.auth.routes import auth_bp
    from app.chat.routes import chat_rest_bp

    flask_app.register_blueprint(character_bp)
    flask_app.register_blueprint(action_bp)
    flask_app.register_blueprint(auth_bp)
    flask_app.register_blueprint(chat_rest_bp)

    socketio.init_app(flask_app)

    # Start your background thread here
    # socketio.start_background_task(check_inactive_users)

    return flask_app