"""
Demo: What MiroFish Simulator actually does well.

The accessibility analysis is DETERMINISTIC and RELIABLE.
It doesn't rely on LLM "not knowing" things - it uses:
- Flesch-Kincaid formula (math)
- Vocabulary database (5000+ words with grade mappings)
- Curriculum standards (what's taught when)

This is genuinely useful for content review.
"""

import asyncio
import sys
sys.path.insert(0, "src")

from mirofish_simulator.accessibility import (
    AccessibilityAnalyzer,
    flesch_kincaid_grade,
    get_word_grade_level,
)


# Test questions at different difficulty levels
QUESTIONS = [
    {
        "name": "AP Government (Hard)",
        "text": "What is the primary function of the Electoral College?",
        "options": [
            "To directly elect members of Congress",
            "To formally elect the President and Vice President",
            "To approve Supreme Court nominations",
            "To ratify constitutional amendments"
        ],
        "target_grade": 5,
    },
    {
        "name": "Simple Civics",
        "text": "Who makes the laws in the United States?",
        "options": [
            "The President",
            "Congress",
            "The judges",
            "The police"
        ],
        "target_grade": 5,
    },
    {
        "name": "Math (Grade appropriate)",
        "text": "What is 3 × 4?",
        "options": ["7", "10", "12", "15"],
        "target_grade": 3,
    },
]


def demo_reading_level():
    """Show Flesch-Kincaid reading level calculation."""
    print("=" * 60)
    print("DEMO 1: Reading Level Analysis (Flesch-Kincaid)")
    print("=" * 60)
    print()

    sentences = [
        "The cat sat on the mat.",  # Simple
        "The Electoral College formally elects the President.",  # Medium
        "Constitutional amendments require ratification by three-fourths of state legislatures.",  # Complex
    ]

    for sentence in sentences:
        grade = flesch_kincaid_grade(sentence)
        print(f"'{sentence[:50]}...'")
        print(f"  → Reading Level: Grade {grade:.1f}")
        print()


def demo_vocabulary():
    """Show vocabulary grade-level lookup."""
    print("=" * 60)
    print("DEMO 2: Vocabulary Grade Levels")
    print("=" * 60)
    print()

    words = [
        "cat", "dog", "run",           # Elementary
        "government", "election",      # Middle school
        "electoral", "ratification",   # High school
        "jurisprudence", "hegemony",   # College
    ]

    for word in words:
        level = get_word_grade_level(word)
        if level is not None:
            grade_name = "K" if level == 0 else str(level)
            print(f"  '{word}': Grade {grade_name}")
        else:
            print(f"  '{word}': Grade 1-2 (common word)")


async def demo_full_analysis():
    """Show complete accessibility analysis."""
    print()
    print("=" * 60)
    print("DEMO 3: Full Accessibility Analysis")
    print("=" * 60)

    analyzer = AccessibilityAnalyzer()

    for q in QUESTIONS:
        print()
        print(f"--- {q['name']} (Target: Grade {q['target_grade']}) ---")
        print(f"Q: {q['text']}")

        result = await analyzer.analyze(
            content={"text": q["text"], "options": q["options"]},
            target_grade=q["target_grade"],
        )

        # Reading level
        fk = result.reading_level.flesch_kincaid_grade
        accessible = fk <= q["target_grade"]
        print(f"\nReading Level: Grade {fk:.1f} {'✓' if accessible else '✗'}")

        # Vocabulary issues
        if result.vocabulary.issues:
            print(f"\nVocabulary Issues ({len(result.vocabulary.issues)}):")
            for issue in result.vocabulary.issues[:3]:
                print(f"  '{issue.word}': requires grade {issue.grade_required} (target: {q['target_grade']})")
        else:
            print("\nVocabulary: All words appropriate for grade level ✓")

        # Recommendations
        if result.recommendations:
            print(f"\nRecommendations:")
            for rec in result.recommendations[:2]:
                print(f"  - {rec.fix}")

        print()


async def main():
    print("\n🔍 MiroFish Accessibility Analysis Demo\n")
    print("These analyses are DETERMINISTIC and RELIABLE.")
    print("They don't depend on LLM knowledge constraints.\n")

    demo_reading_level()
    demo_vocabulary()
    await demo_full_analysis()

    print("=" * 60)
    print("Summary:")
    print("- Reading level analysis: ✓ Works (Flesch-Kincaid formula)")
    print("- Vocabulary analysis: ✓ Works (5000+ word database)")
    print("- Recommendations: ✓ Works (rule-based)")
    print()
    print("- Agent answer selection: ✗ Unreliable (LLM cheats)")
    print("=" * 60)


if __name__ == "__main__":
    asyncio.run(main())
