"""
Live integration test fixtures and skip guard.

Run:
    RUN_LIVE_TESTS=1 \
    LIVE_BASE_URL=https://cloud.cdata.com/api \
    LIVE_USERNAME=<username> \
    LIVE_PASSWORD=<pat> \
    pytest tests/integration_live/ -v

Required environment variables:
    LIVE_BASE_URL   – Connect AI base URL
    LIVE_USERNAME   – account username
    LIVE_PASSWORD   – account password / PAT

Endpoint routing:
  SELECT  → cursor.execute()     → POST /api/query
  DML     → cursor.executemany() → POST /api/batch  (requires ≥1 parameter set)
  Procs   → cursor.callproc()    → POST /api/exec
"""

import os

import pytest

import cdata_connect

# ---------------------------------------------------------------------------
# Skip all tests in this directory unless RUN_LIVE_TESTS=1
# ---------------------------------------------------------------------------

pytestmark = pytest.mark.skipif(
    os.environ.get("RUN_LIVE_TESTS", "0").lower() not in ("1", "true", "yes"),
    reason="Live environment tests skipped. Set RUN_LIVE_TESTS=1 to enable.",
)


# ---------------------------------------------------------------------------
# Credentials
# ---------------------------------------------------------------------------

def _live_credentials() -> tuple[str, str, str]:
    """Return (base_url, username, password) from environment variables.

    Skips with a clear message if any variable is missing.
    """
    url  = os.environ.get("LIVE_BASE_URL")
    user = os.environ.get("LIVE_USERNAME")
    pwd  = os.environ.get("LIVE_PASSWORD")

    missing = [name for name, val in (
        ("LIVE_BASE_URL", url),
        ("LIVE_USERNAME", user),
        ("LIVE_PASSWORD", pwd),
    ) if not val]

    if missing:
        pytest.skip(
            f"Missing required environment variable(s): {', '.join(missing)}. "
            "Set LIVE_BASE_URL, LIVE_USERNAME, and LIVE_PASSWORD to run live tests."
        )

    return url, user, pwd


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------

@pytest.fixture(scope="module")
def live_con():
    """Module-scoped connection to the live CData Connect AI environment."""
    url, user, pwd = _live_credentials()
    conn = cdata_connect.connect(base_url=url, username=user, password=pwd)
    yield conn
    if conn.is_open:
        conn.close()


@pytest.fixture
def cur(live_con):
    """Function-scoped cursor."""
    c = live_con.cursor()
    yield c
    try:
        c.close()
    except Exception:
        pass
