"""Dependency injection for the Kredo Drift server."""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path

from nacl.signing import SigningKey

from kredo_drift.server.config import get_settings
from kredo_drift.vectorize import Vectorizer


@lru_cache
def get_vectorizer() -> Vectorizer:
    """Cached vectorizer instance."""
    settings = get_settings()
    return Vectorizer(model_name=settings.model_name)


def get_service_signing_key() -> SigningKey:
    """Load or generate the service's Ed25519 signing key.

    The key is stored at the path specified in settings.service_key_path.
    Generated on first use.
    """
    settings = get_settings()
    key_path = settings.service_key_path

    if key_path.exists():
        key_bytes = key_path.read_bytes()
        return SigningKey(key_bytes)

    # Generate new key
    sk = SigningKey.generate()
    key_path.parent.mkdir(parents=True, exist_ok=True)
    key_path.write_bytes(bytes(sk))
    key_path.chmod(0o600)
    return sk


def get_service_pubkey() -> str:
    """Get the service's public key string."""
    sk = get_service_signing_key()
    return f"ed25519:{sk.verify_key.encode().hex()}"
