"""Demo: Teaching Assistant Agent for teaching Python programming."""

import os
from agenai.agents.teaching_assistant import TeachingAssistantAgent
from agenai.agent import AgentConfig, HookRegistry, HookEvent


def demo_basic_usage():
    """Basic usage of Teaching Assistant agent."""
    print("=" * 60)
    print("Teaching Assistant Agent - Basic Usage Demo")
    print("=" * 60)

    agent = TeachingAssistantAgent(
        config=AgentConfig(
            model="claude-sonnet-4-6",
            max_steps=10,
        ),
        difficulty_level="beginner",
    )

    print(f"\nAgent: {agent.name}")
    print(f"Tools available: {[t.name for t in agent.get_tools()]}")

    # Example interactions
    prompts = [
        "Explain what a for loop is in Python with a simple example",
        "Review this code: def add(a, b): return a + b",
        "Create an exercise about Python lists for beginners",
    ]

    for prompt in prompts:
        print(f"\n{'─' * 40}")
        print(f"Student: {prompt}")
        print(f"{'─' * 40}")

        result = agent.run(prompt)

        if result.success:
            print(f"\nAssistant: {result.output[:500]}...")
        else:
            print(f"\nError: {result.error}")


def demo_with_hooks():
    """Demo with observability hooks."""
    print("\n" + "=" * 60)
    print("Teaching Assistant Agent - With Observability Hooks")
    print("=" * 60)

    hooks = HookRegistry()

    @hooks.on(HookEvent.TOOL_START)
    def on_tool_start(data):
        print(f"  [Tool] Using: {data.tool_name}")

    @hooks.on(HookEvent.TOOL_END)
    def on_tool_end(data):
        if data.tool_result:
            status = "Success" if data.tool_result.success else "Failed"
            print(f"  [Tool] {data.tool_name}: {status}")

    agent = TeachingAssistantAgent(
        config=AgentConfig(max_steps=5),
        hooks=hooks,
    )

    result = agent.run("Run this code and explain what it does: print([x**2 for x in range(5)])")

    if result.success:
        print(f"\nResponse: {result.output}")

    print(f"\nSession stats: {agent.get_session_stats()}")


def demo_tools_directly():
    """Demo using tools directly without LLM."""
    print("\n" + "=" * 60)
    print("Teaching Assistant Tools - Direct Usage Demo")
    print("=" * 60)

    from agenai.agents.teaching_assistant.tools import (
        CodeRunnerTool,
        CodeReviewerTool,
        ExerciseGeneratorTool,
        QuizGeneratorTool,
    )

    # 1. Run code
    print("\n1. Code Runner Tool")
    runner = CodeRunnerTool()
    result = runner.execute(code="print('Hello from Teaching Assistant!')")
    print(f"   {result.output}")

    # 2. Review code
    print("\n2. Code Reviewer Tool")
    reviewer = CodeReviewerTool()
    code = '''
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n-1)

print(factorial(5))
'''
    result = reviewer.execute(code=code)
    print(f"   {result.output[:300]}...")

    # 3. Generate exercise
    print("\n3. Exercise Generator Tool")
    exercise_gen = ExerciseGeneratorTool()
    result = exercise_gen.execute(
        topic="functions",
        title="Calculate Factorial",
        description="Write a function that calculates the factorial of a number.",
        difficulty="beginner",
    )
    print(f"   {result.output[:400]}...")

    # 4. Generate quiz
    print("\n4. Quiz Generator Tool")
    quiz_gen = QuizGeneratorTool()
    result = quiz_gen.execute(
        title="Python Basics Quiz",
        topics=["variables", "loops"],
        questions=[
            {
                "type": "multiple_choice",
                "question": "What keyword is used to define a function in Python?",
                "options": ["func", "def", "function", "define"],
                "correct_answer": "B",
                "explanation": "The 'def' keyword is used to define functions in Python.",
            },
        ],
    )
    print(f"   {result.output[:400]}...")


if __name__ == "__main__":
    # Check for API key
    if not os.environ.get("ANTHROPIC_API_KEY"):
        print("Note: ANTHROPIC_API_KEY not set. Running tools-only demo.\n")
        demo_tools_directly()
    else:
        demo_basic_usage()
        demo_with_hooks()
        demo_tools_directly()
