"""
clawID FastAPI application factory.

Usage:
    from clawid.api import create_app
    from clawid.storage import SQLiteStore

    app = create_app(store=SQLiteStore("clawid.db"))
"""

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

from .routes import router
from .. import __version__


def create_app(
    store=None,
    cors_origins: list[str] | None = None,
    title: str = "clawID API",
) -> FastAPI:
    """
    Create and configure the FastAPI application.

    Args:
        store:        a ClawIDStore backend (SQLite, Postgres, Mongo, Redis).
                      If None, the /v1/asset endpoints are disabled and
                      detect() returns only the embedded payload.
        cors_origins: list of allowed CORS origins (default: all).
        title:        API title shown in the OpenAPI docs.
    """
    app = FastAPI(
        title=title,
        description=(
            "Digital watermarking for AI-generated images.\n\n"
            "Embed invisible or visible clawID watermarks, then detect them later "
            "to prove authorship and trace asset provenance."
        ),
        version=__version__,
        docs_url="/docs",
        redoc_url="/redoc",
    )

    # Store is available to all route handlers via request.app.state.store
    app.state.store = store

    # CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=cors_origins or ["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(router)
    return app
