"""
Coview persistence layer — session-scoped SQLite storage.

Each session has its own state (`folio`, `highlights`, `notes`, `strokes`,
`arrows`) backed by `data/coview.db`. State is materialized into an in-memory
dict on first access, then write-through on every mutation.

Public API:
    init_db()                                  — create tables if missing
    load_session(session_id) -> dict           — state dict
    save_note(session_id, note)                — append
    save_highlight(session_id, hl)             — append
    replace_highlights(session_id, folio, highlights) — replace per-folio set
    save_stroke(session_id, st)                — append
    save_arrow(session_id, ar)                 — append
    set_folio(session_id, folio)               — folio change + clears annotations
    clear_annotations(session_id)              — highlights/strokes/arrows → []
"""
from __future__ import annotations

import hashlib
import json
import os
import sqlite3
import threading
from datetime import datetime
from pathlib import Path
from typing import Any


PROJECT_ROOT = Path(__file__).resolve().parents[2]

_lock = threading.Lock()


def db_path() -> Path:
    return Path(os.environ.get("HAIL_COVIEW_DB_PATH", str(PROJECT_ROOT / "data" / "coview.db")))


def _conn() -> sqlite3.Connection:
    path = db_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    c = sqlite3.connect(str(path), isolation_level=None)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    c.execute("PRAGMA foreign_keys=ON")
    return c


def init_db() -> None:
    with _lock, _conn() as c:
        c.executescript(
            """
            CREATE TABLE IF NOT EXISTS sessions (
                id           TEXT PRIMARY KEY,
                folio        TEXT NOT NULL DEFAULT 'f1r',
                created_at   TEXT NOT NULL,
                last_active  TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS notes (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id  TEXT NOT NULL,
                ts          TEXT NOT NULL,
                owner       TEXT,
                text        TEXT,
                action_json TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_notes_session ON notes(session_id, id);
            CREATE TABLE IF NOT EXISTS highlights (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id  TEXT NOT NULL,
                folio       TEXT NOT NULL,
                type        TEXT,
                x INTEGER, y INTEGER, w INTEGER, h INTEGER,
                label       TEXT,
                owner       TEXT,
                color       TEXT,
                ts          TEXT NOT NULL,
                fingerprint TEXT
            );
            CREATE INDEX IF NOT EXISTS idx_highlights_sf ON highlights(session_id, folio);
            CREATE TABLE IF NOT EXISTS strokes (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id  TEXT NOT NULL,
                folio       TEXT NOT NULL,
                points_json TEXT NOT NULL,
                color       TEXT,
                width       INTEGER,
                owner       TEXT,
                ts          TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_strokes_sf ON strokes(session_id, folio);
            CREATE TABLE IF NOT EXISTS arrows (
                id          INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id  TEXT NOT NULL,
                folio       TEXT NOT NULL,
                x1 INTEGER, y1 INTEGER, x2 INTEGER, y2 INTEGER,
                color       TEXT,
                label       TEXT,
                owner       TEXT,
                ts          TEXT NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_arrows_sf ON arrows(session_id, folio);
            """
        )
        # Migration: add fingerprint column to existing DBs
        try:
            with _conn() as c:
                c.execute("ALTER TABLE highlights ADD COLUMN fingerprint TEXT")
        except Exception:
            pass  # column already exists


def _ensure_session(c: sqlite3.Connection, session_id: str) -> None:
    now = datetime.now().isoformat(timespec="seconds")
    c.execute(
        "INSERT OR IGNORE INTO sessions (id, folio, created_at, last_active) "
        "VALUES (?, 'f1r', ?, ?)",
        (session_id, now, now),
    )
    c.execute(
        "UPDATE sessions SET last_active = ? WHERE id = ?",
        (now, session_id),
    )


def load_session(session_id: str) -> dict:
    """Return the current state dict for this session — shape identical to
    the legacy in-memory `_coview_state`."""
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        row = c.execute(
            "SELECT folio FROM sessions WHERE id = ?", (session_id,)
        ).fetchone()
        folio = row["folio"] if row else "f1r"

        def q(sql: str):
            return c.execute(sql, (session_id, folio)).fetchall()

        highlights = [
            {
                "action": "highlight",
                "type": r["type"],
                "x": r["x"], "y": r["y"], "w": r["w"], "h": r["h"],
                "label": r["label"] or "",
                "owner": r["owner"],
                "color": r["color"],
                "time": r["ts"],
            }
            for r in q(
                "SELECT * FROM highlights WHERE session_id = ? AND folio = ? ORDER BY id"
            )
        ]
        strokes = [
            {
                "action": "stroke",
                "type": "stroke",
                "points": json.loads(r["points_json"]),
                "color": r["color"],
                "width": r["width"],
                "owner": r["owner"],
                "time": r["ts"],
            }
            for r in q(
                "SELECT * FROM strokes WHERE session_id = ? AND folio = ? ORDER BY id"
            )
        ]
        arrows = [
            {
                "action": "arrow",
                "type": "arrow",
                "x1": r["x1"], "y1": r["y1"], "x2": r["x2"], "y2": r["y2"],
                "color": r["color"],
                "label": r["label"] or "",
                "owner": r["owner"],
                "time": r["ts"],
            }
            for r in q(
                "SELECT * FROM arrows WHERE session_id = ? AND folio = ? ORDER BY id"
            )
        ]
        notes = [
            {
                "action": "note",
                "owner": r["owner"],
                "text": r["text"],
                "time": r["ts"],
            }
            for r in c.execute(
                "SELECT owner, text, ts FROM notes WHERE session_id = ? "
                "ORDER BY id DESC LIMIT 300",
                (session_id,),
            ).fetchall()
        ][::-1]  # back to chronological

        return {
            "folio": folio,
            "highlights": highlights,
            "strokes": strokes,
            "arrows": arrows,
            "notes": notes,
        }


def save_note(session_id: str, note: dict) -> None:
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        c.execute(
            "INSERT INTO notes (session_id, ts, owner, text, action_json) "
            "VALUES (?, ?, ?, ?, ?)",
            (
                session_id,
                note.get("time") or datetime.now().strftime("%H:%M:%S"),
                note.get("owner"),
                note.get("text"),
                json.dumps(note),
            ),
        )


def _highlight_fingerprint(session_id: str, folio: str, hl: dict) -> str:
    payload = f"{session_id}:{folio}:{hl.get('type','rect')}:{hl.get('x',0)}:{hl.get('y',0)}:{hl.get('w',0)}:{hl.get('h',0)}:{hl.get('label','')}"
    return hashlib.sha256(payload.encode()).hexdigest()


def _insert_highlight(c: sqlite3.Connection, session_id: str, folio: str, hl: dict) -> None:
    fingerprint = _highlight_fingerprint(session_id, folio, hl)
    c.execute(
        "INSERT INTO highlights "
        "(session_id, folio, type, x, y, w, h, label, owner, color, ts, fingerprint) "
        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        (
            session_id, folio,
            hl.get("type", "rect"),
            int(hl.get("x", 0)), int(hl.get("y", 0)),
            int(hl.get("w", 0)), int(hl.get("h", 0)),
            hl.get("label") or "",
            hl.get("owner"),
            hl.get("color"),
            hl.get("time") or datetime.now().strftime("%H:%M:%S"),
            fingerprint,
        ),
    )


def save_highlight(session_id: str, folio: str, hl: dict) -> None:
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        _insert_highlight(c, session_id, folio, hl)


def replace_highlights(session_id: str, folio: str, highlights: list[dict[str, Any]]) -> None:
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        c.execute(
            "DELETE FROM highlights WHERE session_id = ? AND folio = ?",
            (session_id, folio),
        )
        for hl in highlights:
            _insert_highlight(c, session_id, folio, hl)


def save_stroke(session_id: str, folio: str, st: dict) -> None:
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        c.execute(
            "INSERT INTO strokes "
            "(session_id, folio, points_json, color, width, owner, ts) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                session_id, folio,
                json.dumps(st.get("points") or []),
                st.get("color"),
                int(st.get("width", 3)),
                st.get("owner"),
                st.get("time") or datetime.now().strftime("%H:%M:%S"),
            ),
        )


def save_arrow(session_id: str, folio: str, ar: dict) -> None:
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        c.execute(
            "INSERT INTO arrows "
            "(session_id, folio, x1, y1, x2, y2, color, label, owner, ts) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (
                session_id, folio,
                int(ar.get("x1", 0)), int(ar.get("y1", 0)),
                int(ar.get("x2", 0)), int(ar.get("y2", 0)),
                ar.get("color"),
                ar.get("label") or "",
                ar.get("owner"),
                ar.get("time") or datetime.now().strftime("%H:%M:%S"),
            ),
        )


def set_folio(session_id: str, folio: str) -> None:
    """Change folio. Does NOT clear annotations — those are folio-scoped in
    queries, so they survive per-folio naturally."""
    with _lock, _conn() as c:
        _ensure_session(c, session_id)
        c.execute(
            "UPDATE sessions SET folio = ?, last_active = ? WHERE id = ?",
            (folio, datetime.now().isoformat(timespec="seconds"), session_id),
        )


def clear_annotations(session_id: str, folio: str) -> None:
    """Wipe all annotations for a session+folio (the `clear` action)."""
    with _lock, _conn() as c:
        for tbl in ("highlights", "strokes", "arrows"):
            c.execute(
                f"DELETE FROM {tbl} WHERE session_id = ? AND folio = ?",
                (session_id, folio),
            )
