"""Tests for 9 theological research scenarios: diachronic word study,
commentary comparison, deuterocanonical exegesis, patristic catena,
resurrection corpus, Emmaus Eucharist, Catholic social teaching,
Advent prophecy chain, and Hebrew chesed study.

Each scenario (S1-S9) maps to one test function that chains multiple
tools: verse retrieval, Strong's study, lexicon lookup, commentary
search, cross-references, and translation comparison. Tests skip
gracefully when dependencies or network are unavailable.
"""

from __future__ import annotations
import pytest


# =============================================================================
# IMPORT GUARDS (following test_catholic_theologian_scenarios.py conventions)
# =============================================================================

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

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

# --- acc2 tools ---
try:
    from accordance_services.tools.acc2 import (
        find_ot_quotations, find_parallel_passages,
    )
    _has_acc2 = True
except Exception:
    _has_acc2 = False

# --- MCP server tools ---
_has_mcp_tools = False
_has_lexicons = False
_has_commentaries = False
_has_search_index = False
try:
    from accordance_mcp_server import (
        study_strongs_number,
        search_commentaries,
        search_commentary_text,
        search_commentaries_for_topic,
        get_commentary_text,
        compare_translations,
        compare_catholic_translations,
        find_cross_references,
        search_dictionary,
        compare_definitions,
        search_all,
    )
    _has_mcp_tools = True

    import accordance_mcp_server as _mcp_srv
    if getattr(_mcp_srv, "_lexicon_modules", None) and len(_mcp_srv._lexicon_modules) > 0:
        _has_lexicons = True
    if getattr(_mcp_srv, "_commentary_modules", None) and len(_mcp_srv._commentary_modules) > 0:
        _has_commentaries = True
    if getattr(_mcp_srv, "_search_index", None) is not None:
        _has_search_index = True
except Exception:
    pass

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


# =============================================================================
# S1 — DIACHRONIC WORD STUDY: צדק / δικαιοσύνη (Righteousness)
# =============================================================================

@pytest.mark.skipif(not _has_mcp_tools, reason="MCP server tools not available")
class TestS1DiachronicRighteousness:
    """S1: Hebrew H6666 / Greek G1343 — righteousness word study."""

    def test_strongs_h6666_hebrew_righteousness(self):
        """H6666 (צדקה — righteousness) lexicon lookup returns content."""
        result = study_strongs_number("H6666")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_strongs_g1343_greek_righteousness(self):
        """G1343 (δικαιοσύνη — righteousness) lexicon lookup returns content."""
        result = study_strongs_number("G1343")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_verses_by_strongs_h6666(self):
        """search_verses_by_strongs('H6666') returns verse references."""
        if not _has_strongs_tools:
            pytest.skip("Strong's tools not available")
        result = search_verses_by_strongs("H6666")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_compare_definitions_righteousness(self):
        """compare_definitions for δικαιοσύνη returns multi-lexicon output."""
        if not _has_lexicons:
            pytest.skip("No lexicon modules available")
        result = compare_definitions("δικαιοσύνη")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    @pytest.mark.skipif(not _has_network, reason="Requires network")
    def test_commentaries_romans_3_21(self):
        """search_commentaries('Romans 3:21') discusses righteousness."""
        result = search_commentaries("Romans 3:21")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20


# =============================================================================
# S2 — SCHOLARLY COMMENTARY COMPARISON ON JOHN 1:1 (Logos)
# =============================================================================

@pytest.mark.skipif(not _has_commentaries, reason="No commentary modules available")
class TestS2CommentaryComparisonLogos:
    """S2: Compare Hermeneia vs JFB on John 1:1. Search lexicons for logos."""

    def test_hermeneia_john_1_1(self):
        """Hermeneia on John 1:1 returns scholarly commentary text."""
        result = get_commentary_text("Hermeneia NT-21", "John 1:1")
        # May not have Hermeneia installed; handle gracefully
        assert result is not None
        assert isinstance(result, str) and len(result) > 5

    def test_jfb_john_1_1(self):
        """JFB on John 1:1 returns classic commentary text."""
        result = get_commentary_text("JFB", "John 1:1")
        assert result is not None
        assert isinstance(result, str) and len(result) > 5

    def test_hermeneia_and_jfb_different(self):
        """Hermeneia and JFB return different commentary text."""
        a = get_commentary_text("Hermeneia NT-21", "John 1:1")
        b = get_commentary_text("JFB", "John 1:1")
        if "[Commentary " in a or "[Commentary " in b:
            pytest.skip("One or both commentaries not installed")
        assert a != b, "Expected different commentary text for Hermeneia vs JFB"

    def test_search_logos_commentaries(self):
        """search_commentary_text('Logos') returns results across commentaries."""
        result = search_commentary_text("Logos")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    @pytest.mark.skipif(not _has_lexicons, reason="No lexicon modules available")
    def test_search_logos_lexicon(self):
        """search_dictionary('logos') returns Greek lexicon entries."""
        result = search_dictionary("logos")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20


# =============================================================================
# S3 — DEUTEROCANONICAL EXEGESIS: WISDOM 7:25-26 (Sophia Christology)
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS3DeuterocanonicalWisdom:
    """S3: Wisdom 7:25-26 — Sophia Christology in deuterocanon."""

    def test_wisdom_7_25_nabre(self):
        """Wisdom 7:25 NABRE returns text about Wisdom as breath of God."""
        vr = get_verse("Wisdom 7:25", "NABRE")
        assert vr is not None and len(vr.text) > 10

    def test_wisdom_7_26_nabre(self):
        """Wisdom 7:26 NABRE returns text about Wisdom as mirror/reflection."""
        vr = get_verse("Wisdom 7:26", "NABRE")
        assert vr is not None and len(vr.text) > 10

    def test_commentaries_wisdom_7_25(self):
        """search_commentaries('Wisdom 7:25') handles deuterocanonical refs."""
        if not _has_mcp_tools or not _has_commentaries:
            pytest.skip("MCP commentary tools not available")
        result = search_commentaries("Wisdom 7:25")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_catholic_translations_wisdom(self):
        """compare_catholic_translations for Wisdom 7:25 returns text."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = compare_catholic_translations("Wisdom 7:25")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    @pytest.mark.skipif(not _has_lexicons, reason="No lexicon modules available")
    def test_search_sophia(self):
        """search_dictionary('Sophia') returns Greek lexicon entries."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = search_dictionary("σοφία")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_cross_references_wisdom_7_25(self):
        """find_cross_references('Wisdom 7:25') runs without crash."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = find_cross_references("Wisdom 7:25")
        assert result is not None
        assert isinstance(result, str)


# =============================================================================
# S4 — PATRISTIC CITATION CHAIN: JOHN 1:14 (Word-Flesh)
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS4PatristicJohn1_14:
    """S4: John 1:14 — σκηνόω (G4637) tabernacling, Irenaeus citations."""

    def test_john_1_14_kjv(self):
        """John 1:14 KJV returns 'the Word was made flesh and dwelt among us'."""
        vr = get_verse("John 1:14", "KJV")
        assert vr is not None
        assert len(vr.text) > 10
        assert "flesh" in vr.text.lower()

    def test_strongs_g4637_skenoo(self):
        """study_strongs_number('G4637') for σκηνόω (dwelt/tabernacled)."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = study_strongs_number("G4637")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_commentaries_john_1_14(self):
        """search_commentaries('John 1:14') returns entries."""
        if not _has_mcp_tools or not _has_commentaries:
            pytest.skip("MCP commentary tools not available")
        result = search_commentaries("John 1:14")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_search_irenaeus(self):
        """search_all('Irenaeus') or search_commentary_text finds patristic refs."""
        if not _has_mcp_tools or not _has_search_index:
            pytest.skip("Search index not available")
        result = search_all("Irenaeus", max_results=5)
        assert result is not None
        assert isinstance(result, str)

    def test_cross_references_john_1_14(self):
        """find_cross_references('John 1:14') returns Exodus/incarnation links."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = find_cross_references("John 1:14")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20


# =============================================================================
# S5 — RESURRECTION CORPUS: 2 MACC 7 + DANIEL 12 + 1 COR 15
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS5ResurrectionCorpus:
    """S5: 2 Maccabees 7, Daniel 12, 1 Corinthians 15 — resurrection hope."""

    def test_2macc_7_9_nabre(self):
        """2 Maccabees 7:9 NABRE returns resurrection hope text."""
        vr = get_verse("2 Maccabees 7:9", "NABRE")
        assert vr is not None and len(vr.text) > 10

    def test_daniel_12_2_nabre(self):
        """Daniel 12:2 NABRE returns resurrection prophecy."""
        vr = get_verse("Daniel 12:2", "NABRE")
        assert vr is not None
        assert len(vr.text) > 10
        assert "awake" in vr.text.lower() or "sleep" in vr.text.lower() or "dust" in vr.text.lower()

    def test_ot_quotations_1cor_15_4(self):
        """find_ot_quotations('1 Corinthians 15:4') verifies .acc2 OT-in-NT."""
        if not _has_acc2:
            pytest.skip("acc2 module not available")
        result = find_ot_quotations("1 Corinthians 15:4")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_catholic_translations_2macc_7_9(self):
        """compare_catholic_translations('2 Maccabees 7:9') returns content."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = compare_catholic_translations("2 Maccabees 7:9")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_commentaries_daniel_12_2(self):
        """search_commentaries('Daniel 12:2') returns entries."""
        if not _has_mcp_tools or not _has_commentaries:
            pytest.skip("MCP commentary tools not available")
        result = search_commentaries("Daniel 12:2")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10


# =============================================================================
# S6 — EMMAUS EUCHARISTIC MEDITATION (Luke 24:30-31)
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS6Emmaus:
    """S6: Luke 24:30-31 — Emmaus breaking of bread, cross-references."""

    def test_luke_24_30_31_nabre(self):
        """Luke 24:30-31 NABRE returns the Emmaus breaking of bread text."""
        vr = get_verse("Luke 24:30-31", "NABRE")
        assert vr is not None and len(vr.text) > 20
        assert "bread" in vr.text.lower() or "break" in vr.text.lower() or "eyes" in vr.text.lower()

    def test_commentaries_luke_24_30(self):
        """search_commentaries('Luke 24:30') returns entries."""
        if not _has_mcp_tools or not _has_commentaries:
            pytest.skip("MCP commentary tools not available")
        result = search_commentaries("Luke 24:30")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_cross_references_luke_24_30(self):
        """find_cross_references('Luke 24:30') returns related verses."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = find_cross_references("Luke 24:30")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_compare_luke_24_31(self):
        """compare_translations Luke 24:31 in NABRE, KJV, ESV."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = compare_translations("Luke 24:31", "NABRE,KJV,ESV")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_search_breaking_of_bread(self):
        """search_all('breaking of bread') returns results."""
        if not _has_mcp_tools or not _has_search_index:
            pytest.skip("Search index not available")
        result = search_all("breaking of bread", max_results=5)
        assert result is not None
        assert isinstance(result, str) and len(result) > 5


# =============================================================================
# S7 — CATHOLIC SOCIAL TEACHING: MATTHEW 25 SHEEP AND GOATS
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS7CatholicSocialTeaching:
    """S7: Matthew 25 sheep and goats, Luke 4:18 Nazareth manifesto."""

    def test_search_poor(self):
        """search_all('poor', max_results=10) returns results."""
        if not _has_mcp_tools or not _has_search_index:
            pytest.skip("Search index not available")
        result = search_all("poor", max_results=10)
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_matthew_25_35_40_nabre(self):
        """Matthew 25:35-40 NABRE returns full sheep and goats pericope."""
        vr = get_verse("Matthew 25:35-40", "NABRE")
        assert vr is not None and len(vr.text) > 30
        assert "hungry" in vr.text.lower() or "thirsty" in vr.text.lower() or "prison" in vr.text.lower()

    def test_search_social_justice(self):
        """search_commentaries_for_topic or search_all for social justice."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        if _has_commentaries:
            result = search_commentaries_for_topic("social justice", max_results=5)
        elif _has_search_index:
            result = search_all("social justice", max_results=5)
        else:
            pytest.skip("Neither commentaries nor search index available")
        assert result is not None
        assert isinstance(result, str) and len(result) > 5

    def test_catholic_luke_4_18(self):
        """compare_catholic_translations('Luke 4:18') for Nazareth manifesto."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = compare_catholic_translations("Luke 4:18")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_ot_quotations_luke_4_18(self):
        """find_ot_quotations('Luke 4:18') finds Isaiah 61 reference."""
        if not _has_acc2:
            pytest.skip("acc2 module not available")
        result = find_ot_quotations("Luke 4:18")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10


# =============================================================================
# S8 — ADVENT PROPHECY CHAIN: ISAIAH 7:14 → MATTHEW 1:23
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS8AdventProphecy:
    """S8: Isaiah 7:14 → Matthew 1:23 — virgin/Immanuel prophecy chain."""

    def test_isaiah_7_14_nabre(self):
        """Isaiah 7:14 NABRE returns virgin/Immanuel text."""
        vr = get_verse("Isaiah 7:14", "NABRE")
        assert vr is not None and len(vr.text) > 10
        assert "young woman" in vr.text.lower() or "emmanuel" in vr.text.lower() or "sign" in vr.text.lower()

    def test_ot_quotations_matthew_1_23(self):
        """find_ot_quotations('Matthew 1:23') returns Isaiah reference."""
        if not _has_acc2:
            pytest.skip("acc2 module not available")
        result = find_ot_quotations("Matthew 1:23")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_commentaries_isaiah_7_14(self):
        """search_commentaries('Isaiah 7:14') returns entries."""
        if not _has_mcp_tools or not _has_commentaries:
            pytest.skip("MCP commentary tools not available")
        result = search_commentaries("Isaiah 7:14")
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_catholic_translations_isaiah_7_14(self):
        """compare_catholic_translations('Isaiah 7:14') returns comparisons."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = compare_catholic_translations("Isaiah 7:14")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_parallel_passages_matthew_1_23(self):
        """find_parallel_passages('Matthew 1:23') verifies acc2 modules."""
        if not _has_acc2:
            pytest.skip("acc2 module not available")
        result = find_parallel_passages("Matthew 1:23")
        assert result is not None
        assert isinstance(result, str)


# =============================================================================
# S9 — HEBREW WORD STUDY: PSALM 51 CHESED (Lent)
# =============================================================================

@pytest.mark.skipif(not _has_network, reason="Requires network")
class TestS9Psalm51Chesed:
    """S9: Psalm 51:1-4 — H2617 (chesed/mercy) word study for Lent."""

    def test_psalm_51_1_4_nabre(self):
        """Psalm 51:1-4 NABRE returns the Miserere text; check key verse 3."""
        vr = get_verse("Psalm 51:3", "NABRE")
        assert vr is not None and len(vr.text) > 10
        assert "mercy" in vr.text.lower() or "compassion" in vr.text.lower() or "pity" in vr.text.lower() or "gracious" in vr.text.lower()

    def test_strongs_h2617_chesed(self):
        """study_strongs_number('H2617') for chesed/mercy returns content."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = study_strongs_number("H2617")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_verses_by_strongs_h2617(self):
        """search_verses_by_strongs('H2617', max_results=10) returns verses."""
        if not _has_strongs_tools:
            pytest.skip("Strong's tools not available")
        result = search_verses_by_strongs("H2617", max_results=10)
        assert result is not None
        assert isinstance(result, str) and len(result) > 10

    def test_compare_psalm_51_1(self):
        """compare_translations Psalm 51:1 in NABRE, DRB, KJV."""
        if not _has_mcp_tools:
            pytest.skip("MCP tools not available")
        result = compare_translations("Psalm 51:1", "NABRE,DRB,KJV")
        assert result is not None
        assert isinstance(result, str) and len(result) > 20

    def test_drb_translation_available(self):
        """Verify DRB (Douay-Rheims) is available via get_verse."""
        vr = get_verse("Psalm 51:1", "DRB")
        assert vr is not None
        assert len(vr.text) > 5, "DRB translation should return text for Psalm 51:1"
