"""SQLite cache for Memory Gateway user credentials."""

from __future__ import annotations

import sqlite3
import time
from pathlib import Path


class MemoryGatewayUserStore:
    """Persist `user_id -> user_key` mappings returned by Memory Gateway."""

    def __init__(self, db_path: str | Path) -> None:
        self.db_path = Path(db_path)
        self.db_path.parent.mkdir(parents=True, exist_ok=True)
        self._init_schema()

    def get_user_key(self, user_id: str) -> str | None:
        with self._connect() as conn:
            row = conn.execute(
                "SELECT user_key FROM memory_gateway_users WHERE user_id = ?",
                (user_id,),
            ).fetchone()
        return str(row[0]) if row else None

    def save_user_key(self, user_id: str, user_key: str) -> None:
        now = time.time()
        with self._connect() as conn:
            conn.execute(
                """
                INSERT INTO memory_gateway_users (user_id, user_key, created_at, updated_at)
                VALUES (?, ?, ?, ?)
                ON CONFLICT(user_id) DO UPDATE SET
                    user_key = excluded.user_key,
                    updated_at = excluded.updated_at
                """,
                (user_id, user_key, now, now),
            )

    def _init_schema(self) -> None:
        with self._connect() as conn:
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS memory_gateway_users (
                    user_id TEXT PRIMARY KEY,
                    user_key TEXT NOT NULL,
                    created_at REAL NOT NULL,
                    updated_at REAL NOT NULL
                )
                """
            )

    def _connect(self) -> sqlite3.Connection:
        return sqlite3.connect(str(self.db_path))
