"""Standalone FastAPI server for Memory System API."""
from __future__ import annotations

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from .api import router
from .config import Config, load_config, set_config


app = FastAPI(title="Memory System API", version="0.1.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.include_router(router)


def create_app(config: Config | None = None) -> FastAPI:
    if config:
        set_config(config)
    return app


def main() -> None:
    import argparse
    import uvicorn

    parser = argparse.ArgumentParser(description="Memory System API")
    parser.add_argument("--config", default="config.yaml", help="Config file path")
    parser.add_argument("--host", default=None, help="Bind host")
    parser.add_argument("--port", type=int, default=None, help="Bind port")
    args = parser.parse_args()

    config = load_config(args.config)
    if args.host:
        config.server.host = args.host
    if args.port:
        config.server.port = args.port
    set_config(config)

    uvicorn.run(app, host=config.server.host, port=config.server.port, log_level=config.logging.level.lower())


if __name__ == "__main__":
    main()
