"""Session 76: Seven Sacraments — 9 chained workflow scenarios.

Covers Eucharist (John 6:53), Holy Orders (1 Tim 4:14, 2 Tim 1:6),
Purgatory (2 Macc 12), RCIA Baptism (Rom 6), Confession (James 5:16),
Baptism Catechesis (Acts 2), Anointing (James 5:14), Apostolic Succession
(1 Tim 4:14 + Acts 14:23), and Matrimony (Ephesians 5). Each test
chains 4-5 tool calls into a single ≤15-line function validating
multi-step sacramental workflows.
"""
from __future__ import annotations
import pytest

# =============================================================================
# IMPORT GUARDS
# =============================================================================

# --- Canon ---
_has_canon = False
try:
    _has_canon = True
except Exception:
    pass

# --- Bible API ---
_has_bible_api = False
try:
    from accordance_parser.bible_api import get_verse
    _has_bible_api = True
except Exception:
    pass

# --- MCP server ---
_has_mcp = False
try:
    from accordance_mcp_server import (
        search_all, search_commentaries, search_commentaries_for_topic,
        compare_translations, compare_catholic_translations, find_cross_references,
        study_strongs_number, get_strongs_for_verse, get_dictionary_entry,
        search_dictionary_content, search_dictionary,
    )
    _has_mcp = True
except Exception:
    pass

# --- Strong's search tools ---
_has_strongs_tools = False
try:
    from accordance_services.tools.strongs import search_verses_by_strongs
    _has_strongs_tools = True
except Exception:
    pass

# --- Search tools ---
_has_search_tools = False
try:
    from accordance_services.tools.search import search_verses_by_term
    _has_search_tools = True
except Exception:
    pass

# --- Multi-tools (compare_commentaries) ---
_has_multi_tools = False
try:
    from accordance_services.tools.commentary import compare_commentaries
    _has_multi_tools = True
except Exception:
    pass

# --- Acc2 tools ---
_has_acc2_tools = False
try:
    from accordance_services.tools.acc2 import find_ot_quotations
    _has_acc2_tools = True
except Exception:
    pass

# --- Network detection ---
_has_network = False
try:
    r = get_verse("Genesis 1:1", "KJV")
    if r and r.text:
        _has_network = True
except Exception:
    pass


# =============================================================================
# HELPER
# =============================================================================

def _ok(text) -> bool:
    """Return True if text is a non-empty string with no Python traceback."""
    if not isinstance(text, str) or not text.strip():
        return False
    return "Traceback (most recent call last)" not in text


# =============================================================================
# S1 — Eucharist Chain with Commentary Comparison (John 6:53)
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s1_eucharist_john6_53_chain():
    """S1: Eucharist — topic search → NABRE → compare commentaries → Strong's chain."""
    if not (_has_multi_tools and _has_strongs_tools):
        pytest.skip("multi_tools or strongs_tools not importable")
    r1 = search_commentaries_for_topic("Eucharist", max_results=5)
    assert _ok(r1), f"commentary topic failed: {r1[:100]}"
    vr = get_verse("John 6:53", "NABRE")
    assert vr and "flesh" in vr.text.lower()
    r3 = compare_commentaries("John 6:53", "Catholic SB-3,JFB")
    assert _ok(r3), f"compare_commentaries failed: {r3[:100]}"
    r4 = study_strongs_number("G5315")
    assert _ok(r4), f"study_strongs_number failed: {r4[:100]}"
    r5 = search_verses_by_strongs("G5315", max_results=10)
    assert isinstance(r5, str) and len(r5) > 0


# =============================================================================
# S2 — Holy Orders / Ordination (1 Tim 4:14, 2 Tim 1:6)
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s2_holy_orders_ordination_chain():
    """S2: Ordination — 1 Tim 4:14 + 2 Tim 1:6 → commentaries → Acts 6:6 cross-refs."""
    v1 = get_verse("1 Timothy 4:14", "NABRE")
    assert v1 and ("hands" in v1.text.lower() or "gift" in v1.text.lower())
    v2 = get_verse("2 Timothy 1:6", "NABRE")
    assert v2 and ("hands" in v2.text.lower() or "gift" in v2.text.lower())
    r3 = search_commentaries("1 Timothy 4:14")
    assert _ok(r3), f"search_commentaries failed: {r3[:100]}"
    r4 = find_cross_references("Acts 6:6")
    assert _ok(r4), f"find_cross_references failed: {r4[:100]}"


# =============================================================================
# S3 — Purgatory Defense from 2 Maccabees 12
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s3_purgatory_defense_2macc12_chain():
    """S3: Purgatory — 2 Macc 12:46 → translations → topic search → 1 Cor 3:15."""
    vr = get_verse("2 Maccabees 12:46", "NABRE")
    assert vr is not None and len(vr.text) > 20
    r2 = compare_translations("2 Maccabees 12:46", "NABRE,DRB")
    assert _ok(r2), f"compare_translations failed: {r2[:100]}"
    r3 = search_commentaries_for_topic("purgatory", max_results=5)
    assert _ok(r3), f"commentary topic failed: {r3[:100]}"
    r4 = find_cross_references("1 Corinthians 3:15")
    assert _ok(r4), f"find_cross_references failed: {r4[:100]}"


# =============================================================================
# S4 — RCIA Baptism Prep with Dictionaries + Commentary
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s4_rcia_baptism_prep_chain():
    """S4: RCIA Baptism — dictionary → Easton lookup → Romans 6:3-4 → commentary."""
    r1 = search_dictionary_content("baptism", max_results=5)
    assert _ok(r1), f"dictionary content failed: {r1[:100]}"
    r2 = get_dictionary_entry("Easton", "baptism")
    assert _ok(r2) or "not found" in r2.lower(), f"Easton failed: {r2[:100]}"
    vr = get_verse("Romans 6:3-4", "NABRE")
    assert vr and "baptiz" in vr.text.lower()
    r4 = search_commentaries("Romans 6:4")
    assert _ok(r4), f"search_commentaries failed: {r4[:100]}"


# =============================================================================
# S5 — Confession / Reconciliation — James 5:16
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s5_confession_james5_16_chain():
    """S5: Confession — search_all → NABRE → Catholic translations → commentary → xrefs."""
    r1 = search_all("confess", max_results=10)
    assert _ok(r1), f"search_all failed: {r1[:100]}"
    vr = get_verse("James 5:16", "NABRE")
    assert vr and "confess" in vr.text.lower()
    r3 = compare_catholic_translations("James 5:16")
    assert _ok(r3), f"catholic translations failed: {r3[:100]}"
    r4 = search_commentaries("James 5:16")
    assert _ok(r4), f"search_commentaries failed: {r4[:100]}"
    r5 = find_cross_references("James 5:16")
    assert _ok(r5), f"find_cross_references failed: {r5[:100]}"


# =============================================================================
# S6 — Baptism Catechesis — Acts 2:38-39
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s6_baptism_catechesis_acts2_chain():
    """S6: Baptism catechesis — dictionary → term search → Acts 2 → translations."""
    if not _has_search_tools:
        pytest.skip("search tools not importable")
    r1 = search_dictionary_content("baptism", max_results=5)
    assert _ok(r1), f"dictionary content failed: {r1[:100]}"
    r2 = search_verses_by_term("baptize", max_results=10)
    assert isinstance(r2, str) and len(r2) > 0
    vr = get_verse("Acts 2:38-39", "NABRE")
    assert vr and ("repent" in vr.text.lower() or "baptiz" in vr.text.lower())
    r4 = search_commentaries("Acts 2:38")
    assert _ok(r4), f"search_commentaries failed: {r4[:100]}"
    r5 = compare_translations("Acts 2:38", "NABRE,ESV,KJV")
    assert _ok(r5), f"compare_translations failed: {r5[:100]}"


# =============================================================================
# S7 — Anointing of the Sick — James 5:14-15
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s7_anointing_sick_james5_chain():
    """S7: Anointing — search_all → NABRE → commentary → translations → Strong's."""
    r1 = search_all("anointing", max_results=10)
    assert _ok(r1), f"search_all failed: {r1[:100]}"
    vr = get_verse("James 5:14-15", "NABRE")
    assert vr and ("anoint" in vr.text.lower() or "oil" in vr.text.lower())
    r3 = search_commentaries("James 5:14")
    assert _ok(r3), f"search_commentaries failed: {r3[:100]}"
    r4 = compare_catholic_translations("James 5:14")
    assert _ok(r4), f"catholic translations failed: {r4[:100]}"
    r5 = get_strongs_for_verse("James 5:14")
    assert _ok(r5), f"get_strongs_for_verse failed: {r5[:100]}"


# =============================================================================
# S8 — Holy Orders / Apostolic Succession (1 Tim 4:14, Acts 14:23)
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s8_holy_orders_apostolic_chain():
    """S8: Apostolic succession — presbyter search → 1 Tim 4:14 → OT quotations."""
    if not _has_search_tools:
        pytest.skip("search tools not importable")
    r1 = search_verses_by_term("presbyter", max_results=10)
    assert isinstance(r1, str) and len(r1) > 0
    vr = get_verse("1 Timothy 4:14", "NABRE")
    assert vr and ("hands" in vr.text.lower() or "gift" in vr.text.lower())
    r3 = search_commentaries("1 Timothy 4:14")
    assert _ok(r3), f"search_commentaries failed: {r3[:100]}"
    r4 = find_ot_quotations("Acts 14:23")
    assert isinstance(r4, str) and len(r4) > 0


# =============================================================================
# S9 — Matrimony — Ephesians 5:25-33
# =============================================================================

@pytest.mark.skipif(not _has_mcp, reason="MCP server not importable")
@pytest.mark.skipif(not _has_network, reason="Requires network")
def test_s9_matrimony_ephesians5_chain():
    """S9: Matrimony — dictionary → NABRE → topic search → translations → Strong's."""
    r1 = search_dictionary("marriage")
    assert isinstance(r1, str) and len(r1) > 0
    vr = get_verse("Ephesians 5:25-33", "NABRE")
    assert vr and ("husbands" in vr.text.lower() or "wives" in vr.text.lower()
                   or "church" in vr.text.lower())
    r3 = search_all("marriage", max_results=5)
    assert _ok(r3), f"search_all failed: {r3[:100]}"
    r4 = compare_catholic_translations("Ephesians 5:25")
    assert _ok(r4), f"catholic translations failed: {r4[:100]}"
    r5 = get_strongs_for_verse("Ephesians 5:25")
    assert _ok(r5), f"get_strongs_for_verse failed: {r5[:100]}"
