"""
Demo test fixtures.

Provides a live DB connector and helpers for the demo test suite.
All tests assume the gateway is configured and the DB is reachable.
"""

import pytest
from modules.security.rootAccess import getRootDbAppConnector
from modules.datamodels.datamodelUam import Mandate, UserInDB
from modules.datamodels.datamodelFeatures import FeatureInstance
from modules.datamodels.datamodelMembership import UserMandate


@pytest.fixture(scope="session")
def db():
    """Root DB connector (session-scoped, reused across all tests)."""
    return getRootDbAppConnector()


@pytest.fixture(scope="session")
def demoConfig():
    """The investor demo config instance."""
    from modules.demoConfigs import _getDemoConfigByCode
    cfg = _getDemoConfigByCode("investor-demo-2026")
    assert cfg is not None, "Demo config 'investor-demo-2026' not found — check modules/demoConfigs/"
    return cfg


# ---------------------------------------------------------------------------
# Mandate helpers — function-scoped so they always reflect current DB state
# (test_removeAndReload recreates mandates with new IDs mid-session)
# ---------------------------------------------------------------------------

@pytest.fixture
def mandateHappylife(db):
    """HappyLife AG mandate (must exist after bootstrap load)."""
    records = db.getRecordset(Mandate, recordFilter={"name": "happylife"})
    assert records, "Mandate 'happylife' not found — run demo config load first"
    return records[0]


@pytest.fixture
def mandateAlpina(db):
    """Alpina Treuhand AG mandate (must exist after bootstrap load)."""
    records = db.getRecordset(Mandate, recordFilter={"name": "alpina-treuhand"})
    assert records, "Mandate 'alpina-treuhand' not found — run demo config load first"
    return records[0]


@pytest.fixture
def demoUser(db):
    """Patrick Helvetia user (must exist after bootstrap load)."""
    records = db.getRecordset(UserInDB, recordFilter={"username": "patrick.helvetia"})
    assert records, "User 'patrick.helvetia' not found — run demo config load first"
    return records[0]


def _getFeatureInstances(db, mandateId: str, featureCode: str):
    """Helper: get feature instances for a mandate + code."""
    return db.getRecordset(FeatureInstance, recordFilter={
        "mandateId": mandateId,
        "featureCode": featureCode,
    })
