# cache.py
import sqlite3
import hashlib
import os
from pathlib import Path



CACHE_DIR = Path.home() / ".goodgute"
CACHE_PATH = CACHE_DIR / "cache.db"

CACHE_DIR.mkdir(parents=True, exist_ok=True)
def ensure_cache():
    CACHE_DIR.mkdir(parents=True, exist_ok=True)

    # 如果文件不存在 → 创建新表
    if not os.path.exists(CACHE_PATH):
        _create_cache_db()
        return

    # 如果存在 → 检查 schema
    conn = sqlite3.connect(CACHE_PATH)
    cur = conn.cursor()

    try:
        cur.execute("PRAGMA table_info(translations)")
        cols = [row[1] for row in cur.fetchall()]
    except sqlite3.OperationalError:
        cols = []

    # 如果结构不完整 → 删除旧文件并重建
    if "translation" not in cols:
        conn.close()
        os.remove(CACHE_PATH)
        _create_cache_db()
        return

    conn.close()


def _create_cache_db():
    conn = sqlite3.connect(CACHE_PATH)
    cur = conn.cursor()

    cur.execute("""
        CREATE TABLE translations (
            hash TEXT PRIMARY KEY,
            text TEXT,
            translation TEXT
        )
    """)
    conn.commit()
    conn.close()


def _hash(text: str) -> str:
    """Create a stable hash for the text."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def cache_get(text: str) -> str | None:
    """Return cached translation or None."""

    key = _hash(text)

    conn = sqlite3.connect(CACHE_PATH)
    cur = conn.cursor()

    cur.execute("SELECT translation FROM translations WHERE hash = ?", (key,))
    row = cur.fetchone()

    conn.close()

    if row:
        return row[0]
    return None


def cache_set(text: str, translation: str):
    """Store translation into database."""

    key = _hash(text)

    conn = sqlite3.connect(CACHE_PATH)
    cur = conn.cursor()

    cur.execute("""
        INSERT OR REPLACE INTO translations (hash, text, translation)
        VALUES (?, ?, ?)
    """, (key, text, translation))

    conn.commit()
    conn.close()

def cache_clean():
    if not CACHE_PATH.exists():
        return
    conn = sqlite3.connect(CACHE_PATH)
    cur = conn.cursor()
    cur.execute("DELETE FROM translations")
    conn.commit()
    conn.close()