"""Phase 2 verification tests.
Checks that BDB Complete parsing and Hebrew encoding work correctly,
and that no regressions occurred in BDAG/HALOT parsing.
"""
import sys
sys.path.insert(0, ".")

from accordance_parser.lexicon_module import LexiconModule
from accordance_parser.discovery import discover_modules


def test_all_lexicons_load():
    """Verify all 19 lexicon modules can be loaded without errors."""
    print("=" * 60)
    print("TEST: Load all lexicon modules")
    print("=" * 60)

    mods = discover_modules()
    lexicon_mods = {k: v for k, v in mods.items() if v["type"] in (3, 4)}

    failures = []
    for abbr, info in sorted(lexicon_mods.items()):
        try:
            lex = LexiconModule(info["path"])
            count = len(lex.headwords())
            print(f"  OK  {abbr:25s} -> {count} entries")
        except Exception as e:
            msg = f"  FAIL {abbr}: {e}"
            print(msg)
            failures.append(msg)

    if failures:
        print(f"\n  {len(failures)} FAILURES")
        return False
    print(f"  All {len(lexicon_mods)} lexicons loaded successfully")
    return True


def test_bdb_lookups():
    """Test BDB Complete Strong's number and Hebrew headword lookups."""
    print("\n" + "=" * 60)
    print("TEST: BDB Complete Lookups")
    print("=" * 60)

    mods = discover_modules()
    info = mods.get("BDB Complete")
    if not info:
        print("SKIP: Not installed")
        return True

    lex = LexiconModule(info["path"])
    failures = []

    # BDB Strong's numbers should return definitions
    tests = [
        ("H120", "man"),
        ("H430", "God"),
        ("H1254", "create"),
        ("H100", "rush"),
        ("H179", "camel"),
    ]
    for sn, fragment in tests:
        result = lex.lookup(sn)
        if result and fragment in result:
            print(f"  OK  Strong's {sn} -> '{fragment}' found")
        else:
            msg = f"  FAIL Strong's {sn}"
            print(msg)
            if result:
                print(f"       got: {result[:100]}")
            else:
                print("       got: None")
            failures.append(msg)

    # BDB Hebrew headwords should work too
    hebrew_tests = [
        ("\u05d0\u05dc\u05d4\u05d9\u05dd", "God"),  # אלהים
        ("\u05d1\u05e8\u05d0", "create"),             # ברא
    ]
    for hw, fragment in hebrew_tests:
        result = lex.lookup(hw)
        if result and fragment in result:
            print(f"  OK  Hebrew '{hw}' -> '{fragment}' found")
        else:
            msg = f"  FAIL Hebrew '{hw}'"
            print(msg)
            if result:
                print(f"       got: {result[:100]}")
            else:
                print("       got: None")
            failures.append(msg)

    if failures:
        print(f"\n  {len(failures)} FAILURES")
        return False
    print("  ALL PASSED")
    return True


def test_bdag_regression():
    """Verify BDAG lookups still work after encoding changes."""
    print("\n" + "=" * 60)
    print("TEST: BDAG (no regression)")
    print("=" * 60)

    mods = discover_modules()
    info = mods.get("BDAG")
    if not info:
        print("SKIP: Not installed")
        return True

    lex = LexiconModule(info["path"])
    count = len(lex.headwords())
    print(f"  Entry count: {count}")
    assert count >= 4000, f"Expected >= 4000 BDAG entries, got {count}"

    result = lex.lookup("\u03bb\u03cc\u03b3\u03bf\u03c2")  # λόγος
    assert result and "word" in result, "λόγος lookup failed"
    print("  OK  λόγος lookup")

    result = lex.lookup("\u03b8\u03b5\u03cc\u03c2")  # θεός
    assert result and "God" in result, "θεός lookup failed"
    print("  OK  θεός lookup")

    print("  ALL PASSED")
    return True


def test_halot_regression():
    """Verify HALOT loads with expected entry count (no regression)."""
    print("\n" + "=" * 60)
    print("TEST: HALOT (no regression)")
    print("=" * 60)

    mods = discover_modules()
    info = mods.get("HALOT")
    if not info:
        print("SKIP: Not installed")
        return True

    lex = LexiconModule(info["path"])
    count = len(lex.headwords())
    print(f"  Entry count: {count}")
    assert count >= 3500, f"Expected >= 3500 HALOT entries, got {count}"
    print("  ALL PASSED")
    return True


def test_encoding_quality():
    """Verify Hebrew text is properly decoded in BDB results."""
    print("\n" + "=" * 60)
    print("TEST: Hebrew Encoding Quality")
    print("=" * 60)

    mods = discover_modules()
    info = mods.get("BDB Complete")
    if not info:
        print("SKIP: Not installed")
        return True

    lex = LexiconModule(info["path"])

    # H120 should return text with decoded Hebrew headword (אדם)
    result = lex.lookup("H120")
    assert result, "H120 not found"
    # Check for decoded Hebrew (should NOT contain raw 'aD' prefix)
    has_decoded = "\u05d0\u05d3\u05b8\u05dd" in result  # אדָם
    has_raw_hebrew = "aDd" in result or "aD" in result[:10]
    if has_decoded and not has_raw_hebrew:
        print("  OK  H120 has decoded Hebrew headword (אדָם)")
    else:
        print(f"  WARN H120 encoding: decoded={has_decoded} raw={has_raw_hebrew}")
        print(f"       first 80 chars: {result[:80]}")

    # H1254 should have decoded headword (ברא)
    result = lex.lookup("H1254")
    assert result, "H1254 not found"
    has_decoded = "\u05e8\u05b8\u05d0" in result  # רָא
    if has_decoded:
        print("  OK  H1254 has decoded Hebrew root (רָא)")
    else:
        print(f"  WARN H1254 encoding: first 80 chars: {result[:80]}")

    print("  ALL PASSED")
    return True


def main():
    results = {}
    results["Load all 19 lexicons"] = test_all_lexicons_load()
    results["BDB lookups"] = test_bdb_lookups()
    results["Encoding quality"] = test_encoding_quality()
    results["BDAG regression"] = test_bdag_regression()
    results["HALOT regression"] = test_halot_regression()

    print("\n" + "=" * 60)
    print("PHASE 2 VERIFICATION SUMMARY")
    print("=" * 60)
    all_pass = True
    for name, passed in results.items():
        status = "PASS" if passed else "FAIL"
        print(f"  {name:30s} {status}")
        if not passed:
            all_pass = False

    if all_pass:
        print("\n  Phase 2 verification PASSED")
    else:
        print("\n  Phase 2 verification FAILED")

    return 0 if all_pass else 1


if __name__ == "__main__":
    sys.exit(main())
