"""
SQLite store — zero-dependency, great for local dev and single-server deployments.

Usage:
    store = SQLiteStore("clawid.db")          # file-based
    store = SQLiteStore(":memory:")            # in-memory (tests)
"""

import json
import sqlite3
import time
import threading

from .base import ClawIDStore


class SQLiteStore(ClawIDStore):

    def __init__(self, db_path: str = "clawid.db"):
        self._lock = threading.Lock()
        self.conn = sqlite3.connect(db_path, check_same_thread=False)
        self.conn.row_factory = sqlite3.Row
        self._migrate()

    def _migrate(self) -> None:
        with self._lock:
            self.conn.execute("""
                CREATE TABLE IF NOT EXISTS clawid_assets (
                    clawid     TEXT PRIMARY KEY,
                    metadata   TEXT    NOT NULL,
                    created_at REAL    NOT NULL,
                    updated_at REAL    NOT NULL
                )
            """)
            self.conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_created ON clawid_assets(created_at)"
            )
            self.conn.commit()

    def save(self, clawid: str, metadata: dict) -> None:
        now = time.time()
        with self._lock:
            self.conn.execute(
                """
                INSERT INTO clawid_assets (clawid, metadata, created_at, updated_at)
                VALUES (?, ?, ?, ?)
                ON CONFLICT(clawid) DO UPDATE SET
                    metadata   = excluded.metadata,
                    updated_at = excluded.updated_at
                """,
                (clawid, json.dumps(metadata), now, now),
            )
            self.conn.commit()

    def get(self, clawid: str) -> dict | None:
        row = self.conn.execute(
            "SELECT metadata FROM clawid_assets WHERE clawid = ?", (clawid,)
        ).fetchone()
        return json.loads(row["metadata"]) if row else None

    def delete(self, clawid: str) -> bool:
        with self._lock:
            cur = self.conn.execute(
                "DELETE FROM clawid_assets WHERE clawid = ?", (clawid,)
            )
            self.conn.commit()
        return cur.rowcount > 0

    def exists(self, clawid: str) -> bool:
        return self.conn.execute(
            "SELECT 1 FROM clawid_assets WHERE clawid = ?", (clawid,)
        ).fetchone() is not None

    def close(self) -> None:
        self.conn.close()
