import logging
import os
from functools import lru_cache
from typing import Final

import uvicorn
from appkit_commons.ai.openai_client_service import OpenAIClientService
from appkit_commons.configuration.configuration import (
    ApplicationConfig,
    Configuration,
)
from appkit_commons.configuration.logging import init_logging
from appkit_commons.registry import service_registry
from appkit_mcp_bpmn.configuration import BPMNConfig
from appkit_mcp_bpmn.server import create_bpmn_mcp_server
from dotenv import load_dotenv
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware

logger = logging.getLogger(__name__)

load_dotenv()  # Load environment variables from .env file

API_KEY: Final[str] = os.getenv("OPENAI_API_KEY", "your-openai-api-key")
BASE_URL: Final[str] = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")


class ServerConfig(ApplicationConfig):
    mcp_bpmn: BPMNConfig | None = None


@lru_cache(maxsize=1)
def configure() -> Configuration[ServerConfig]:
    logger.debug("--- Configuring application settings ---")
    return service_registry().configure(
        ServerConfig,
        env_file="/.env",
    )


def main():
    configuration = configure()
    init_logging(configuration)
    service = OpenAIClientService(
        api_key=API_KEY,
        base_url=BASE_URL,
        on_azure=True,
    )
    service_registry().register(service)

    config = service_registry().get(BPMNConfig)
    mcp = create_bpmn_mcp_server(name="appkit-bpmn-mcp", config=config)

    middleware = [
        Middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
            allow_headers=[
                "mcp-protocol-version",
                "mcp-session-id",
                "Authorization",
                "Content-Type",
            ],
            expose_headers=["mcp-session-id"],
        )
    ]
    app = mcp.http_app(middleware=middleware, path="/mcp", stateless_http=True)
    uvicorn.run(app, host="127.0.0.1", port=8000)


if __name__ == "__main__":
    main()
