import logging
import sys

from flask import Flask, request, jsonify
from flask_cors import CORS

from api.auth_api import auth_api, mail
from api.child_api import child_api
from api.image_api import image_api
from api.reward_api import reward_api
from api.task_api import task_api
from api.user_api import user_api
from config.version import get_full_version
from db.default import initializeImages, createDefaultTasks, createDefaultRewards
from events.broadcaster import Broadcaster
from events.sse import sse_response_for_user, send_to_user

# Configure logging once at application startup
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    stream=sys.stdout,
    force=True  # Override any existing config
)
logger = logging.getLogger(__name__)

app = Flask(__name__)
#CORS(app, resources={r"/api/*": {"origins": ["http://localhost:3000", "http://localhost:5173"]}})
app.register_blueprint(child_api)
app.register_blueprint(reward_api)
app.register_blueprint(task_api)
app.register_blueprint(image_api)
app.register_blueprint(auth_api)
app.register_blueprint(user_api)

app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME='ryan.kegel@gmail.com',
    MAIL_PASSWORD='ruyj hxjf nmrz buar',
    MAIL_DEFAULT_SENDER='ryan.kegel@gmail.com',
    FRONTEND_URL='https://localhost:5173',  # Adjust as needed
    SECRET_KEY='supersecretkey'  # Replace with a secure key in production
)
mail.init_app(app)

CORS(app)

@app.route("/version")
def api_version():
    return jsonify({"version": get_full_version()})

@app.route("/events")
def events():
    # Authenticate user or read a token
    user_id = request.args.get("user_id")
    if not user_id:
        return {"error": "Missing user_id"}, 400


    return sse_response_for_user(user_id)


@app.route("/notify/<user_id>")
def notify_user(user_id):
    # Example trigger
    send_to_user(user_id, {
        "type": "notification",
        "message": f"Hello {user_id}, this is a private message!"
    })

    return {"status": "sent"}

def start_background_threads():
    broadcaster = Broadcaster()
    broadcaster.daemon = True
    broadcaster.start()

# TODO: implement users
initializeImages()
createDefaultTasks()
createDefaultRewards()
start_background_threads()


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