import os
import signal
import sys

from dotenv import load_dotenv
from flask import Flask

if __name__ == "__main__":
    load_dotenv()
    api_port = int(os.getenv("VITE_API_PORT", "5000"))
    app = Flask(__name__)
    app_mode = os.getenv("APP_MODE", "agenthub")
    from backend.setup import setup_app

    setup_app(
        app, db_url=os.getenv("DATABASE_URL"), workload_folder_path=os.getenv("db_folder_path"), app_mode=app_mode
    )

    # TODO : do this also in backend.py
    def signal_handler(sig, frame):
        print("\nShutting down gracefully...")
        publishing_service = app.config.get("PUBLISHING_SERVICE")
        if publishing_service:
            publishing_service.shutdown()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    app.run(host="127.0.0.1", port=api_port, debug=True)
