"""Wave B2: DatabaseConnectionManager failure contract.

Contract: `with DatabaseConnectionManager(...) as conn` yields a valid
sqlite3.Connection, or the original connection exception propagates -- it
must never swallow the error and bind None (which previously turned a DB
failure into a misleading AttributeError at the call site).

The manual-commit / close / body-exception semantics of __exit__ are
unchanged and are pinned here so a future edit can't regress them. All
runtime uses a temporary DATA_DIR; real InvestmentData is never touched.
"""
import io
import contextlib
import sqlite3

import pytest

from modules import classes
from modules.classes import DatabaseConnectionManager


@pytest.fixture()
def data_dir(tmp_path, monkeypatch):
    monkeypatch.setenv("DATA_DIR", str(tmp_path))
    (tmp_path / "databases").mkdir()
    # Pre-create the default (IDB) DB so a successful connection is possible.
    sqlite3.connect(tmp_path / "databases" / "IDB.db").close()
    return tmp_path


# ---------------------------------------------------------------------------
# A. Successful enter
# ---------------------------------------------------------------------------

def test_enter_returns_a_usable_connection(data_dir):
    with DatabaseConnectionManager() as conn:
        assert isinstance(conn, sqlite3.Connection)
        conn.execute("CREATE TABLE t (x INTEGER)")
        conn.execute("INSERT INTO t VALUES (42)")
        assert conn.execute("SELECT x FROM t").fetchone()[0] == 42


# ---------------------------------------------------------------------------
# B. Connection failure -> original sqlite exception propagates (never None)
# ---------------------------------------------------------------------------

def test_connection_failure_propagates_original_sqlite_exception(data_dir, monkeypatch):
    def boom(db_target=None):
        raise sqlite3.OperationalError("sentinel connection failure")

    # classes.py imported `connection` by name, so patch it there.
    monkeypatch.setattr(classes, "connection", boom)

    captured = io.StringIO()
    with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured):
        with pytest.raises(sqlite3.OperationalError, match="sentinel connection failure"):
            with DatabaseConnectionManager() as conn:
                # Must never reach here with conn=None.
                pytest.fail(f"__enter__ should have raised, got conn={conn!r}")

    # No swallowing print, and specifically not the old message.
    assert "Database connection error" not in captured.getvalue()
    assert captured.getvalue() == ""


def test_manager_never_returns_none_on_failure(data_dir, monkeypatch):
    monkeypatch.setattr(classes, "connection", lambda db_target=None: (_ for _ in ()).throw(
        sqlite3.OperationalError("fail")))
    got = []
    with contextlib.suppress(sqlite3.OperationalError):
        with DatabaseConnectionManager() as conn:
            got.append(conn)
    assert got == []  # body never ran with a None connection


# ---------------------------------------------------------------------------
# C. Body exception propagates unchanged
# ---------------------------------------------------------------------------

def test_body_exception_propagates(data_dir):
    class Sentinel(Exception):
        pass

    with pytest.raises(Sentinel):
        with DatabaseConnectionManager() as conn:
            assert conn is not None
            raise Sentinel()


# ---------------------------------------------------------------------------
# D. Manual-commit semantics (unchanged): __exit__ does not auto-commit
# ---------------------------------------------------------------------------

def test_write_without_explicit_commit_is_not_persisted(data_dir):
    with DatabaseConnectionManager() as conn:
        conn.execute("CREATE TABLE t (x INTEGER)")
        conn.execute("INSERT INTO t VALUES (1)")
        # no conn.commit()
    with DatabaseConnectionManager() as conn:
        # DDL implicitly commits in sqlite, so the table exists, but the
        # uncommitted INSERT was discarded on close.
        assert conn.execute("SELECT COUNT(*) FROM t").fetchone()[0] == 0


def test_write_with_explicit_commit_is_persisted(data_dir):
    with DatabaseConnectionManager() as conn:
        conn.execute("CREATE TABLE t (x INTEGER)")
        conn.execute("INSERT INTO t VALUES (7)")
        conn.commit()
    with DatabaseConnectionManager() as conn:
        assert conn.execute("SELECT x FROM t").fetchone()[0] == 7


# ---------------------------------------------------------------------------
# E. Connection is closed after normal exit
# ---------------------------------------------------------------------------

def test_connection_is_closed_after_exit(data_dir):
    with DatabaseConnectionManager() as conn:
        held = conn
    with pytest.raises(sqlite3.ProgrammingError):
        held.execute("SELECT 1")  # operating on a closed connection


# ---------------------------------------------------------------------------
# 7. Representative class-A route: DB-connect failure surfaces as the sqlite
#    error, not an AttributeError from a None connection.
# ---------------------------------------------------------------------------

def test_class_a_route_failure_is_sqlite_not_attribute_error(client, data_dir, monkeypatch):
    with client.session_transaction() as sess:
        sess.update(user_id=1, access_level="master", first_name="T", last_name="U")

    def boom(db_target=None):
        raise sqlite3.OperationalError("sentinel connection failure")

    monkeypatch.setattr(classes, "connection", boom)

    captured = io.StringIO()
    with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured):
        # PROPAGATE_EXCEPTIONS so the underlying error type is observable
        # rather than swallowed by Flask's 500 page.
        client.application.config["PROPAGATE_EXCEPTIONS"] = True
        with pytest.raises(sqlite3.OperationalError, match="sentinel connection failure"):
            client.get("/crm/agents_with_branches")

    assert "Database connection error" not in captured.getvalue()


# ---------------------------------------------------------------------------
# 8. Graceful class-B call sites stay graceful under the new contract.
# ---------------------------------------------------------------------------

def test_authenticate_user_degrades_gracefully_on_connection_failure(data_dir, monkeypatch):
    from InvestmentManager.middleware import auth

    monkeypatch.setattr(classes, "connection", lambda db_target=None: (_ for _ in ()).throw(
        sqlite3.OperationalError("fail")))
    # authenticate_user wraps the with-block in try/except Exception -> None.
    assert auth.authenticate_user("someone", "secret") is None


def test_get_all_agent_ids_degrades_gracefully_on_connection_failure(data_dir, monkeypatch, app):
    from InvestmentManager.routes import knowledge_center

    monkeypatch.setattr(classes, "connection", lambda db_target=None: (_ for _ in ()).throw(
        sqlite3.OperationalError("fail")))
    with app.app_context():
        assert knowledge_center.get_all_agent_ids() == []
