from __future__ import annotations

import os

from tigrbl import TigrblApp
from tigrbl.shortcuts.engine import engine as build_engine
from swarmauri_crypto_paramiko import ParamikoCrypto
from swarmauri_standard.key_providers import InMemoryKeyProvider
from .orm import Key, KeyVersion

DB_URL = os.getenv("KMS_DATABASE_URL", "sqlite+aiosqlite:///./kms.db")
ENGINE = build_engine(DB_URL)


# API-level hooks (v3): stash shared services into ctx before any handler runs
async def _stash_ctx(ctx):
    global CRYPTO, KEY_PROVIDER
    try:
        CRYPTO
    except NameError:
        CRYPTO = ParamikoCrypto()
    try:
        KEY_PROVIDER
    except NameError:
        KEY_PROVIDER = InMemoryKeyProvider()
    ctx["crypto"] = CRYPTO
    ctx["key_provider"] = KEY_PROVIDER


app = TigrblApp(
    title="Tigrbl-KMS",
    version="0.1.0",
    openapi_url="/openapi.json",
    docs_url="/docs",
    jsonrpc_prefix="/kms/rpc",
    engine=ENGINE,
    router_hooks={"*": {"PRE_TX_BEGIN": [_stash_ctx]}},
)


# Custom ops return raw dicts so no finalize hook needed
app.include_tables([Key, KeyVersion], base_prefix="/kms")
app.attach_diagnostics(prefix="/system")

# Keep package-level contract focused on domain models only.
for _system_model in ("__tigrbl_system_docs__", "__tigrbl_system_routes__"):
    app.tables.pop(_system_model, None)

# Backward-compatible alias used by tests and older integrations.
app.routes = app.router.routes


# Initialize database tables on startup
@app.on_event("startup")
async def startup_event():
    await app.initialize()
