import threading
from backend.db.connection import db_connection


class CatalogState:
    """Thread-safe in-memory cursor over stock_history/price_history's AUTOINCREMENT
    ids. The scraper thread and HTTP handler threads share one process (see
    backend/main.py), so this lets GET /api/last_updated answer "did anything
    change" with zero SQLite queries instead of re-scanning either table."""

    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._latest_stock_id = 0
        self._latest_price_id = 0

    def init_from_db(self) -> None:
        with db_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT MAX(id) FROM stock_history")
            stock_max = cursor.fetchone()[0] or 0
            cursor.execute("SELECT MAX(id) FROM price_history")
            price_max = cursor.fetchone()[0] or 0
        with self._lock:
            self._latest_stock_id = stock_max
            self._latest_price_id = price_max

    def bump_stock(self, new_id: int) -> None:
        with self._lock:
            if new_id > self._latest_stock_id:
                self._latest_stock_id = new_id

    def bump_price(self, new_id: int) -> None:
        with self._lock:
            if new_id > self._latest_price_id:
                self._latest_price_id = new_id

    def snapshot(self) -> tuple[int, int]:
        with self._lock:
            return self._latest_stock_id, self._latest_price_id


catalog_state = CatalogState()
