import sqlite3
from contextlib import contextmanager
from pathlib import Path

DB_PATH = "hive.db"

@contextmanager
def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.execute("PRAGMA foreign_keys = ON")
    try:
        yield conn
    finally:
        conn.commit()
        conn.close()

def init_db():
    schema_file = Path("schema.sql")
    if not schema_file.exists():
        raise FileNotFoundError("schema.sql is missing.")

    with get_db() as conn:
        cur = conn.cursor()
        cur.executescript(schema_file.read_text())
