"""SQLite-backed session store for TUI persistence."""

from __future__ import annotations

import json
import sqlite3
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:  # pragma: no cover
    from cleveragents.tui.app import SessionView


@dataclass(slots=True)
class TuiSessionStore:
    """Manages TUI session persistence using SQLite.

    Database location: ~/.local/state/cleveragents/tui.db
    """

    db_path: Path

    def __init__(self, db_path: Path | None = None) -> None:
        """Initialize the session store.

        Args:
            db_path: Path to the SQLite database.
                Defaults to ~/.local/state/cleveragents/tui.db
        """
        if db_path is None:
            state_dir = Path.home() / ".local" / "state" / "cleveragents"
            state_dir.mkdir(parents=True, exist_ok=True)
            db_path = state_dir / "tui.db"

        self.db_path = db_path
        self._initialize_db()

    def _initialize_db(self) -> None:
        """Initialize the SQLite database schema."""
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("""
                CREATE TABLE IF NOT EXISTS sessions (
                    session_id TEXT PRIMARY KEY,
                    transcript TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            conn.execute("""
                CREATE TABLE IF NOT EXISTS active_session (
                    id INTEGER PRIMARY KEY CHECK (id = 1),
                    session_id TEXT NOT NULL,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)
            conn.commit()

    def save_session(self, session: SessionView) -> None:
        """Save a session to the database.

        Args:
            session: The SessionView to save
        """
        with sqlite3.connect(self.db_path) as conn:
            transcript_json = json.dumps(session.transcript)
            conn.execute(
                """
                INSERT OR REPLACE INTO sessions (session_id, transcript, updated_at)
                VALUES (?, ?, CURRENT_TIMESTAMP)
            """,
                (session.session_id, transcript_json),
            )
            conn.commit()

    def load_session(self, session_id: str) -> SessionView | None:
        """Load a session from the database.

        Args:
            session_id: The ID of the session to load

        Returns:
            The SessionView if found, None otherwise
        """
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.execute(
                """
                SELECT session_id, transcript FROM sessions WHERE session_id = ?
            """,
                (session_id,),
            )
            row = cursor.fetchone()

            if row is None:
                return None

            session_id_result, transcript_json = row
            transcript = json.loads(transcript_json)
            # Import here to avoid circular imports
            from cleveragents.tui.app import SessionView

            return SessionView(session_id=session_id_result, transcript=transcript)

    def set_active_session(self, session_id: str) -> None:
        """Set the active session.

        Args:
            session_id: The ID of the session to set as active
        """
        with sqlite3.connect(self.db_path) as conn:
            conn.execute(
                """
                INSERT OR REPLACE INTO active_session (id, session_id, updated_at)
                VALUES (1, ?, CURRENT_TIMESTAMP)
            """,
                (session_id,),
            )
            conn.commit()

    def get_active_session(self) -> str | None:
        """Get the ID of the active session.

        Returns:
            The session ID if one is set, None otherwise
        """
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.execute("""
                SELECT session_id FROM active_session WHERE id = 1
            """)
            row = cursor.fetchone()
            return row[0] if row else None

    def list_sessions(self) -> list[str]:
        """List all session IDs.

        Returns:
            A list of all session IDs in the database
        """
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.execute("""
                SELECT session_id FROM sessions ORDER BY updated_at DESC
            """)
            return [row[0] for row in cursor.fetchall()]

    def delete_session(self, session_id: str) -> None:
        """Delete a session from the database.

        Args:
            session_id: The ID of the session to delete
        """
        with sqlite3.connect(self.db_path) as conn:
            conn.execute(
                """
                DELETE FROM sessions WHERE session_id = ?
            """,
                (session_id,),
            )
            conn.commit()

    def clear_all(self) -> None:
        """Clear all sessions from the database."""
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("DELETE FROM sessions")
            conn.execute("DELETE FROM active_session")
            conn.commit()
