"""SQLite database connection and initialization."""

from __future__ import annotations

import hashlib
import logging
import secrets
from pathlib import Path

import aiosqlite

logger = logging.getLogger("ecate.db")

_SCHEMA_PATH = Path(__file__).parent / "schema.sql"
_DB_PATH: Path | None = None
_db: aiosqlite.Connection | None = None


async def init_db(db_path: str = "data/ecate.db") -> aiosqlite.Connection:
    """Initialize the database, create tables, and ensure a default API key exists."""
    global _db, _DB_PATH
    _DB_PATH = Path(db_path)
    _DB_PATH.parent.mkdir(parents=True, exist_ok=True)

    _db = await aiosqlite.connect(str(_DB_PATH))
    _db.row_factory = aiosqlite.Row
    await _db.execute("PRAGMA journal_mode=WAL")
    await _db.execute("PRAGMA busy_timeout=5000")

    schema = _SCHEMA_PATH.read_text()
    await _db.executescript(schema)
    await _db.commit()

    # Ensure at least one API key exists
    row = await _db.execute_fetchall("SELECT id FROM api_keys LIMIT 1")
    if not row:
        default_key = f"ek-{secrets.token_hex(24)}"
        key_hash = hashlib.sha256(default_key.encode()).hexdigest()
        await _db.execute(
            "INSERT INTO api_keys (id, name, key_hash, default_strategy) VALUES (?, ?, ?, ?)",
            (secrets.token_hex(8), "default", key_hash, "auto"),
        )
        await _db.commit()
        logger.info(f"Generated default API key: {default_key}")
        # Write to a file for convenience
        key_file = _DB_PATH.parent / "default_api_key.txt"
        key_file.write_text(default_key)
        logger.info(f"Default API key written to {key_file}")

    return _db


async def get_db() -> aiosqlite.Connection:
    """Get the active database connection."""
    if _db is None:
        raise RuntimeError("Database not initialized. Call init_db() first.")
    return _db


async def close_db():
    """Close the database connection."""
    global _db
    if _db:
        await _db.close()
        _db = None
