#!/usr/bin/env python3
"""Shared test database setup.

This module is imported by test files to ensure the test DB is initialized
before any app modules load. The actual DB path is managed by conftest.py,
which handles per-worker isolation for parallel pytest-xdist runs.

Import this module BEFORE importing app.models in any test file:
    import tests.test_shared_db  # noqa: F401

What it does:
1. Ensures RELAY_DB_PATH is set (conftest.py does this in pytest_configure)
2. Patches app.db.DB_PATH to point to the test DB
3. Calls app.models.init_db() to create the schema
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Module-level singleton flag — ensures init_db() runs only once per process
_initialized = False


def _setup():
    """Initialize the test database schema.

    Idempotent — only runs once per Python process.
    The DB file path is set by conftest.py (or falls back to a temp file).
    """
    global _initialized
    if _initialized:
        return

    # If conftest already set up the DB path, use it.
    # Otherwise fall back to creating a temp file (for standalone runs).
    db_path = os.environ.get("RELAY_DB_PATH")
    if not db_path:
        import tempfile
        _temp_db = tempfile.NamedTemporaryFile(
            suffix="_standalone.db", delete=False, prefix="agentforms_test_"
        )
        db_path = _temp_db.name
        _temp_db.close()
        os.environ["RELAY_DB_PATH"] = db_path

    # Patch DB_PATH before importing app modules
    import app.db
    app.db.DB_PATH = db_path

    import app.models
    app.models.DB_PATH = db_path
    app.models.init_db()

    _initialized = True


# Run setup at import time
_setup()