"""Schema 元信息读取。"""

from __future__ import annotations

from app.core.db_session import db_conn

CURRENT_SCHEMA_VERSION = 1


def get_schema_version() -> int:
    with db_conn() as conn:
        row = conn.execute("SELECT value FROM schema_meta WHERE key='version'").fetchone()
    if not row:
        return 0
    try:
        return int(row["value"])
    except (TypeError, ValueError):
        return 0


def check_database() -> dict[str, str | int | bool]:
    try:
        version = get_schema_version()
        with db_conn() as conn:
            conn.execute("SELECT 1").fetchone()
        return {
            "ok": True,
            "schema_version": version,
            "expected_schema_version": CURRENT_SCHEMA_VERSION,
            "schema_up_to_date": version >= CURRENT_SCHEMA_VERSION,
        }
    except Exception as exc:
        return {"ok": False, "error": str(exc)}