"""Schema initialization from bundled SQL."""

from __future__ import annotations

import importlib.resources
import logging

import asyncpg

logger = logging.getLogger(__name__)


def _load_sql(filename: str = "schema.sql") -> str:
    """Load a SQL file from the package resources."""
    return importlib.resources.files(__package__).joinpath(filename).read_text("utf-8")


async def ensure_schema(pool: asyncpg.Pool) -> None:
    """Run the DDL in schema.sql against the database.

    The core schema (tables, vector indices) always runs. The ParadeDB BM25
    index is best-effort — skipped if the pg_search extension is unavailable.
    """
    ddl = _load_sql("schema.sql")
    async with pool.acquire() as conn:
        await conn.execute(ddl)

    # Installation registry tables
    try:
        install_ddl = _load_sql("schema_installations.sql")
        async with pool.acquire() as conn:
            await conn.execute(install_ddl)
    except Exception:
        logger.warning("Failed to create installation registry tables", exc_info=True)

    # Agent tables (events, realization evidence, sync state)
    try:
        agent_ddl = _load_sql("schema_agent.sql")
        async with pool.acquire() as conn:
            await conn.execute(agent_ddl)
    except Exception:
        logger.warning("Failed to create agent tables", exc_info=True)

    # User + API key tables
    try:
        users_ddl = _load_sql("schema_users.sql")
        async with pool.acquire() as conn:
            await conn.execute(users_ddl)
    except Exception:
        logger.warning("Failed to create users/api_keys tables", exc_info=True)

    # Coverage snapshot table
    try:
        coverage_ddl = _load_sql("schema_coverage.sql")
        async with pool.acquire() as conn:
            await conn.execute(coverage_ddl)
    except Exception:
        logger.warning("Failed to create coverage snapshots table", exc_info=True)

    # Best-effort: ParadeDB BM25 index
    try:
        bm25_ddl = _load_sql("schema_bm25.sql")
        async with pool.acquire() as conn:
            await conn.execute(bm25_ddl)
    except Exception:
        logger.info(
            "ParadeDB BM25 index not available — skipping (vector + BM25-less search still works)"
        )
