import json
from pathlib import Path

import aiosqlite

from app.config import get_settings

_conn: aiosqlite.Connection | None = None


async def init_db() -> None:
    """Открыть БД, включить WAL, применить schema.sql."""
    global _conn
    settings = get_settings()
    settings.database_path.parent.mkdir(parents=True, exist_ok=True)
    _conn = await aiosqlite.connect(settings.database_path)
    _conn.row_factory = aiosqlite.Row
    await _conn.execute("PRAGMA journal_mode=WAL")
    await _conn.execute("PRAGMA foreign_keys=ON")
    schema = (Path(__file__).with_name("schema.sql")).read_text(encoding="utf-8")
    await _conn.executescript(schema)
    # Колонки, которых нет в старых БД: CREATE TABLE IF NOT EXISTS их не добавит.
    await _try_alter("ALTER TABLE service_samples ADD COLUMN report TEXT")
    await _conn.commit()


async def _try_alter(stmt: str) -> None:
    """ALTER для существующих таблиц; дубликат колонки — норма (уже добавлена)."""
    try:
        await _conn.execute(stmt)
    except aiosqlite.OperationalError as exc:
        if "duplicate column" not in str(exc).lower():
            raise


async def close_db() -> None:
    global _conn
    if _conn is not None:
        await _conn.close()
        _conn = None


def get_db() -> aiosqlite.Connection:
    assert _conn is not None, "database not initialized"
    return _conn


def j(value) -> str:
    """Сериализация JSON-колонок."""
    return json.dumps(value, ensure_ascii=False)