"""
core/database.py
- Simple SQLite history using built-in sqlite3 (no external deps)
"""

import json
import sqlite3
from datetime import datetime
from pathlib import Path
from contextlib import contextmanager


# =====================================================
# DB location — user home dir
# =====================================================
DB_DIR = Path.home() / ".yt_analyzer_pro"
DB_DIR.mkdir(exist_ok=True)
DB_PATH = DB_DIR / "history.db"


# =====================================================
# Connection helper
# =====================================================
@contextmanager
def _conn():
    conn = sqlite3.connect(str(DB_PATH), timeout=10)
    conn.row_factory = sqlite3.Row
    try:
        yield conn
        conn.commit()
    finally:
        conn.close()


# =====================================================
# Schema init
# =====================================================
def _init_db():
    with _conn() as c:
        c.execute("""
            CREATE TABLE IF NOT EXISTS history (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                kind        TEXT    NOT NULL,
                title       TEXT    NOT NULL,
                url         TEXT    DEFAULT '',
                data        TEXT    NOT NULL,
                created_at  TEXT    NOT NULL
            )
        """)
        c.execute("CREATE INDEX IF NOT EXISTS idx_kind ON history(kind)")
        c.execute("CREATE INDEX IF NOT EXISTS idx_created ON history(created_at DESC)")


_init_db()


# =====================================================
# Public API (same as before — no code changes needed elsewhere)
# =====================================================
def save_entry(kind: str, title: str, data: dict, url: str = "") -> int:
    """Save a new history entry. Returns ID."""
    with _conn() as c:
        cur = c.execute(
            "INSERT INTO history (kind, title, url, data, created_at) "
            "VALUES (?, ?, ?, ?, ?)",
            (
                kind,
                (title or "")[:500],
                (url or "")[:500],
                json.dumps(data, ensure_ascii=False),
                datetime.utcnow().isoformat(),
            ),
        )
        return cur.lastrowid


def list_entries(kind: str | None = None, limit: int = 100) -> list[dict]:
    """List history entries, newest first."""
    with _conn() as c:
        if kind:
            rows = c.execute(
                "SELECT id, kind, title, url, created_at FROM history "
                "WHERE kind = ? ORDER BY id DESC LIMIT ?",
                (kind, limit),
            ).fetchall()
        else:
            rows = c.execute(
                "SELECT id, kind, title, url, created_at FROM history "
                "ORDER BY id DESC LIMIT ?",
                (limit,),
            ).fetchall()

    return [
        {
            "id": r["id"],
            "kind": r["kind"],
            "title": r["title"],
            "url": r["url"],
            "created_at": r["created_at"],
        }
        for r in rows
    ]


def get_entry(entry_id: int) -> dict | None:
    """Get full entry with parsed data."""
    with _conn() as c:
        r = c.execute(
            "SELECT id, kind, title, url, data, created_at "
            "FROM history WHERE id = ?",
            (entry_id,),
        ).fetchone()

    if not r:
        return None

    try:
        parsed = json.loads(r["data"])
    except Exception:
        parsed = {}

    return {
        "id": r["id"],
        "kind": r["kind"],
        "title": r["title"],
        "url": r["url"],
        "data": parsed,
        "created_at": r["created_at"],
    }


def delete_entry(entry_id: int) -> None:
    with _conn() as c:
        c.execute("DELETE FROM history WHERE id = ?", (entry_id,))


def clear_all(kind: str | None = None) -> None:
    with _conn() as c:
        if kind:
            c.execute("DELETE FROM history WHERE kind = ?", (kind,))
        else:
            c.execute("DELETE FROM history")


def count_entries(kind: str | None = None) -> int:
    """Count entries (optional helper)."""
    with _conn() as c:
        if kind:
            r = c.execute("SELECT COUNT(*) AS n FROM history WHERE kind = ?", (kind,)).fetchone()
        else:
            r = c.execute("SELECT COUNT(*) AS n FROM history").fetchone()
    return r["n"] if r else 0