"""Site visit statistics API."""

from __future__ import annotations

from fastapi import APIRouter

from core.db import conn

router = APIRouter()


@router.post("/visit")
def record_visit():
    """Record a page visit. Increments today's count."""
    sql = """
        MERGE INTO site_visits sv
        USING (SELECT TRUNC(SYSDATE) AS d FROM dual) src
        ON (sv.visit_date = src.d)
        WHEN MATCHED THEN UPDATE SET sv.visit_count = sv.visit_count + 1
        WHEN NOT MATCHED THEN INSERT (visit_date, visit_count) VALUES (src.d, 1)
    """
    with conn() as c:
        c.cursor().execute(sql)
    return {"ok": True}


@router.get("/visits")
def get_visits():
    """Return today's visit count and all-time total."""
    sql_today = """
        SELECT NVL(visit_count, 0) FROM site_visits WHERE visit_date = TRUNC(SYSDATE)
    """
    sql_total = """
        SELECT NVL(SUM(visit_count), 0) FROM site_visits
    """
    with conn() as c:
        cur = c.cursor()
        cur.execute(sql_today)
        row = cur.fetchone()
        today = int(row[0]) if row else 0
        cur.execute(sql_total)
        total = int(cur.fetchone()[0])
    return {"today": today, "total": total}
