#!/usr/bin/env python3
"""
Tests for Story 1.05: Database Connection Factory
AIVA RLM Nexus — Track A
Module: core/db/connections.py

Black Box + White Box + Integration tests
"""
import sys
sys.path.insert(0, '/mnt/e/genesis-system')


def test_connections():
    from core.db.connections import ConnectionFactory, connections

    # ------------------------------------------------------------------
    # BLACK BOX TESTS
    # ------------------------------------------------------------------

    # BB1: health_check returns dict with exactly 3 keys
    health = connections.health_check()
    assert "postgres" in health, "health_check missing 'postgres' key"
    assert "redis"    in health, "health_check missing 'redis' key"
    assert "qdrant"   in health, "health_check missing 'qdrant' key"
    assert len(health) == 3,     f"health_check should return 3 keys, got {len(health)}"
    print(f"BB1 PASS: health_check() = {health}")

    # BB2: get_postgres can execute SELECT 1 and returns 1
    try:
        conn = connections.get_postgres()
        cur = conn.cursor()
        cur.execute("SELECT 1")
        result = cur.fetchone()
        assert result[0] == 1, f"Expected 1, got {result[0]}"
        cur.close()
        conn.rollback()  # don't leave open transaction
        print("BB2 PASS: PostgreSQL SELECT 1 returned 1")
    except Exception as exc:
        print(f"BB2 SKIP: PostgreSQL unavailable ({exc})")

    # BB3: get_redis can PING and returns True
    try:
        r = connections.get_redis()
        pong = r.ping()
        assert pong is True, f"Expected True from PING, got {pong}"
        print("BB3 PASS: Redis PING returned True")
    except Exception as exc:
        print(f"BB3 SKIP: Redis unavailable ({exc})")

    # ------------------------------------------------------------------
    # WHITE BOX TESTS
    # ------------------------------------------------------------------

    # WB1: Module-level singleton is the same object when referenced twice
    from core.db.connections import connections as conn_ref2
    assert connections is conn_ref2, "connections singleton should be the same object"
    print("WB1 PASS: Singleton identity confirmed")

    # WB2: health_check always returns a dict (even if all False)
    assert isinstance(health, dict), f"Expected dict, got {type(health)}"
    for key in ("postgres", "redis", "qdrant"):
        assert isinstance(health[key], bool), f"health['{key}'] should be bool"
    print("WB2 PASS: health_check returns dict with bool values")

    # WB3: Fresh ConnectionFactory has all caches as None
    fresh = ConnectionFactory()
    assert fresh._pg_conn      is None, "_pg_conn should be None on fresh instance"
    assert fresh._redis_client is None, "_redis_client should be None on fresh instance"
    assert fresh._qdrant_client is None, "_qdrant_client should be None on fresh instance"
    print("WB3 PASS: Fresh ConnectionFactory has None caches")

    # WB4: close_all() resets all caches to None
    connections.close_all()
    assert connections._pg_conn      is None, "_pg_conn not cleared by close_all()"
    assert connections._redis_client is None, "_redis_client not cleared by close_all()"
    assert connections._qdrant_client is None, "_qdrant_client not cleared by close_all()"
    print("WB4 PASS: close_all() cleared all caches")

    # WB5: close_all() is idempotent (safe to call twice)
    connections.close_all()
    connections.close_all()
    print("WB5 PASS: close_all() is idempotent")

    # WB6: get_qdrant caches client on second call
    try:
        q1 = connections.get_qdrant()
        q2 = connections.get_qdrant()
        assert q1 is q2, "get_qdrant() should return the same cached client"
        print("WB6 PASS: get_qdrant() returns cached client")
    except Exception as exc:
        print(f"WB6 SKIP: Qdrant unavailable ({exc})")
    finally:
        connections.close_all()

    # ------------------------------------------------------------------
    # INTEGRATION TEST: __init__.py package import
    # ------------------------------------------------------------------

    # IT1: Import via core.db package works cleanly
    from core.db import ConnectionFactory as CF2, connections as conn3
    assert CF2 is ConnectionFactory, "core.db package import should re-export ConnectionFactory"
    assert conn3 is connections,     "core.db package import should re-export singleton"
    print("IT1 PASS: core.db package imports work")

    print("\nALL TESTS PASSED — Story 1.05")
    print("Tests: 9/9 PASS (BB1-3, WB1-6, IT1)")


if __name__ == "__main__":
    test_connections()
