# File: /db/UserPreferenceStore.py
import os
from pathlib import Path
import sqlite3
from loguru import logger

class UserPreferenceStore:
    """
    Simple key/value store for user preferences, backed by SQLite.
    """
    def __init__(self, db_path: str = "user_prefs.db"):
        self.db_path = db_path
        self._init_db()

    def _init_db(self):
        Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("""
                CREATE TABLE IF NOT EXISTS preferences (
                    key   TEXT PRIMARY KEY,
                    value TEXT
                )
            """)
        logger.debug("UserPreferenceStore DB ready → %s", self.db_path)

    def get(self, key: str, default: str = "") -> str:
        with sqlite3.connect(self.db_path) as conn:
            row = conn.execute(
                "SELECT value FROM preferences WHERE key = ?",
                (key,)
            ).fetchone()
            return row[0] if row else default

    def set(self, key: str, value: str):
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("""
                INSERT INTO preferences(key, value)
                VALUES (?, ?)
                ON CONFLICT(key) DO UPDATE SET value = excluded.value
            """, (key, value))
