from fastapi import FastAPI
import sqlite3

DB_PATH = "/shared_data/detections.db"

app = FastAPI(title="NIDS Detections API")


def get_connection():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


@app.get("/health")
def health():
    return {"status": "ok"}


@app.get("/detections")
def get_detections():
    """Return all detection rows, oldest first (same shape as the old direct SQLite read)."""
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM detections ORDER BY id ASC")
    rows = [dict(row) for row in cursor.fetchall()]
    conn.close()
    return rows


@app.get("/active_flows")
def get_active_flows():
    """Return the current in-progress flow count."""
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT active_flows_count FROM system_status WHERE id = 1")
    row = cursor.fetchone()
    conn.close()
    return {"active_flows_count": row["active_flows_count"] if row else 0}
