from flask import g
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_wtf.csrf import CSRFProtect
from flask_cors import CORS

# Initialize extensions
db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
csrf = CSRFProtect()
cors = CORS()

# Inisialisasi Flask-Limiter
# Use a custom key function to differentiate between API and non-API requests
def api_key_limit_func():
    """
    Custom key function for the rate limiter.
    It uses the API key if the request is authenticated,
    otherwise it falls back to the remote IP address.
    """
    if hasattr(g, 'api_key') and g.api_key:
        # use the API key ID for authenticated requests
        # This assumes g.api_key is set in the request context
        return str(g.api_key.id)
    else:
        # Fallback to remote address for unauthenticated requests
        return get_remote_address()

# Initialize limiter with default storage (in-memory)
limiter = Limiter(
    key_func=get_remote_address,
    #key_func=api_key_limit_func,
    # Reasonable limits for web app with AJAX polling
    default_limits=["3000 per day", "600 per hour"],
    storage_uri="memory://", # or use Redis for production: "redis://localhost:6379"
)
