# if you later decide to store articles in the DB (SQLAlchemy), views would go into the Article table directly (which you already have with the views column) and analytics.py becomes redundant. If you go the markdown route, you'd keep analytics.py as-is.


import os
import sqlite3
from contextlib import contextmanager

class Analytics:
    def __init__(self, db_path:str):
        os.makedirs(os.path.dirname(db_path), exist_ok=True)
        self.db_path = db_path
        self._init_db()

    @contextmanager
    def _conn(self):
        conn = sqlite3.connect(self.db_path, timeout=5)
        try:
            yield conn
        finally:
            conn.close()

    def _init_db(self):
        with self._conn() as conn:
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS views (
                    slug TEXT PRIMARY KEY,
                    views INTEGER NOT NULL DEFAULT 0
                )
                """
            )
            conn.commit()

    def increment_view(self, slug:str) -> int:
        with self._conn() as conn:
            conn.execute(
                """
                INSERT INTO views (slug, views)
                VALUES (?, 1)
                ON CONFLICT(slug) DO UPDATE SET views = views.views + 1
                """,
                (slug,),
            )
            conn.commit()
            cur = conn.execute("SELECT views FROM views WHERE slug = ?", (slug,))
            row = cur.fetchone()
            return int(row[0]) if row else 0

    def get_views(self, slug:str) -> int:
        with self._conn() as conn:
            cur = conn.execute("SELECT views FROM views WHERE slug = ?", (slug,))
            row = cur.fetchone()
            return int(row[0]) if row else 0
