"""
BiasClear Database — Encrypted Connection Factory

Provides a single `get_connection()` function used by both the audit chain
and learning ring. When `BIASCLEAR_DB_KEY` is set, connections use sqlcipher3
with AES-256 encryption. When unset, falls back to standard sqlite3
(development mode).

Usage:
    from biasclear.database import get_connection

    conn = get_connection("biasclear_audit.db")
    # Use conn exactly like sqlite3.Connection — same API.
"""

from __future__ import annotations

import os
import sqlite3
from typing import Union

# Try to import sqlcipher3; if unavailable, encryption isn't possible.
try:
    import sqlcipher3
    _HAS_SQLCIPHER = True
except ImportError:
    _HAS_SQLCIPHER = False

# Environment variable for the encryption key.
# If unset, databases are plaintext (dev mode).
_DB_KEY: str | None = os.environ.get("BIASCLEAR_DB_KEY")


def get_connection(
    db_path: str,
    db_key: str | None = None,
) -> Union[sqlite3.Connection, "sqlcipher3.Connection"]:
    """
    Open a database connection, encrypted if a key is available.

    Priority:
        1. Explicit `db_key` argument
        2. `BIASCLEAR_DB_KEY` environment variable
        3. Falls back to plaintext sqlite3

    Args:
        db_path: Path to the database file.
        db_key: Optional encryption key. Overrides env var.

    Returns:
        Connection object (sqlite3 or sqlcipher3, same DB-API 2.0 interface).

    Raises:
        RuntimeError: If a key is provided but sqlcipher3 is not installed.
    """
    key = db_key or _DB_KEY

    if key:
        if not _HAS_SQLCIPHER:
            raise RuntimeError(
                "BIASCLEAR_DB_KEY is set but sqlcipher3 is not installed. "
                "Install with: pip install sqlcipher3"
            )
        conn = sqlcipher3.connect(db_path)
        conn.execute(f"PRAGMA key='{key}'")
        return conn

    # No key — plaintext mode
    return sqlite3.connect(db_path)


def is_encrypted() -> bool:
    """Check whether encryption is active (key is configured)."""
    return bool(_DB_KEY) and _HAS_SQLCIPHER
