#!/usr/bin/env python3
"""Demo script for the Backend Developer Agent.

This script demonstrates the capabilities and tools available to the backend developer
agent for building the Trax media processing platform.
"""

import sys
from pathlib import Path

# Add src to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))

from agents.backend_developer_agent import get_backend_developer_agent, list_available_tools
from agents.tools.backend_developer_tools import (
    get_tools_by_category,
    get_tools_by_phase,
)


def demo_agent_capabilities():
    """Demonstrate the backend developer agent's capabilities."""
    print("🎯 Backend Developer Agent Demo")
    print("=" * 50)

    # Get the agent
    agent = get_backend_developer_agent()

    print(f"Agent: {agent.name}")
    print(f"Role: {agent.role}")
    print(f"Experience Level: {agent.experience_level}")
    print(f"Salary Range: {agent.salary_range}")
    print(f"Current Focus: {agent.current_focus}")

    print("\n📊 Agent Statistics:")
    print(f"Total Tools Available: {len(agent.get_all_tools())}")
    print(f"Required Skills: {len(agent.get_required_skills())}")

    # Show tools by category
    print("\n🛠️ Tools by Category:")
    tools_by_category = list_available_tools()
    for category, tools in tools_by_category.items():
        print(f"\n{category.upper()}:")
        for tool in tools:
            print(f"  • {tool}")

    # Show current phase tools
    print("\n🎯 Current Phase Tools (Phase 1):")
    phase_tools = agent.get_current_phase_tools()
    for tool in phase_tools:
        print(f"  • {tool.name}")

    # Show required skills
    print("\n📚 Required Skills:")
    skills = agent.get_required_skills()
    for i, skill in enumerate(skills, 1):
        print(f"  {i:2d}. {skill}")


def demo_tool_details():
    """Show detailed information about specific tools."""
    print("\n🔍 Detailed Tool Information")
    print("=" * 50)

    # Get tools by category
    core_tools = get_tools_by_category("core_development")
    db_tools = get_tools_by_category("database")
    ml_tools = get_tools_by_category("ml_integration")

    print("\n💻 Core Development Tools:")
    for tool in core_tools:
        print(f"\n{tool.name}:")
        print(f"  Description: {tool.description}")
        print(f"  Skills: {', '.join(tool.required_skills)}")
        print(f"  Phases: {', '.join(tool.phase_availability)}")
        print("  Capabilities:")
        for cap in tool.capabilities:
            print(f"    • {cap.name}: {cap.description}")
            print(f"      Command: {cap.command}")

    print("\n🗄️ Database Tools:")
    for tool in db_tools:
        print(f"\n{tool.name}:")
        print(f"  Description: {tool.description}")
        print(f"  Skills: {', '.join(tool.required_skills)}")
        print("  Capabilities:")
        for cap in tool.capabilities:
            print(f"    • {cap.name}: {cap.description}")

    print("\n🤖 ML Integration Tools:")
    for tool in ml_tools:
        print(f"\n{tool.name}:")
        print(f"  Description: {tool.description}")
        print(f"  Skills: {', '.join(tool.required_skills)}")
        print("  Capabilities:")
        for cap in tool.capabilities:
            print(f"    • {cap.name}: {cap.description}")


def demo_phase_progression():
    """Show how tools change across development phases."""
    print("\n🚀 Phase Progression")
    print("=" * 50)

    phases = ["v1", "v2", "v3", "v4"]

    for phase in phases:
        print(f"\n📋 Phase {phase.upper()}:")
        phase_tools = get_tools_by_phase(phase)
        for tool in phase_tools:
            print(f"  • {tool.name}")

    # Show phase-specific focus
    print("\n🎯 Phase-Specific Focus:")
    print("v1: Basic Whisper transcription (95% accuracy, <30s for 5min audio)")
    print("v2: AI enhancement (99% accuracy, <35s processing)")
    print("v3: Multi-pass accuracy (99.5% accuracy, <25s processing)")
    print("v4: Speaker diarization (90% speaker accuracy)")


def demo_development_workflow():
    """Show typical development workflow."""
    print("\n⚙️ Development Workflow")
    print("=" * 50)

    workflow_steps = [
        {
            "step": "1. Environment Setup",
            "tools": ["uv Package Manager"],
            "commands": ["uv venv", "source .venv/bin/activate", "uv pip install -e .[dev]"],
        },
        {
            "step": "2. Database Setup",
            "tools": ["PostgreSQL + SQLAlchemy"],
            "commands": ["alembic revision -m 'Initial schema'", "alembic upgrade head"],
        },
        {
            "step": "3. Core Development",
            "tools": ["Python 3.11+ Development", "Protocol-Based Services"],
            "commands": [
                "class TranscriptionService(Protocol):",
                "async def transcribe(self, audio: Path) -> Transcript: ...",
            ],
        },
        {
            "step": "4. ML Integration",
            "tools": ["Whisper Integration"],
            "commands": [
                "from faster_whisper import WhisperModel",
                "model = WhisperModel('distil-large-v3', device='mps')",
            ],
        },
        {
            "step": "5. Testing",
            "tools": ["pytest with Real Files"],
            "commands": ["uv run pytest tests/", "uv run pytest --cov=src"],
        },
        {
            "step": "6. Performance Optimization",
            "tools": ["M3 Hardware Optimization"],
            "commands": [
                "model.transcribe(audio_path, chunk_length=30, overlap=2)",
                "python -m cProfile src/main.py",
            ],
        },
    ]

    for step in workflow_steps:
        print(f"\n{step['step']}:")
        print(f"  Tools: {', '.join(step['tools'])}")
        print("  Commands:")
        for cmd in step["commands"]:
            print(f"    $ {cmd}")


def demo_success_metrics():
    """Show the success metrics the agent needs to achieve."""
    print("\n📈 Success Metrics")
    print("=" * 50)

    metrics = [
        ("Processing Speed", "5-minute audio in <30 seconds"),
        ("Accuracy", "99.5% transcription accuracy with multi-pass"),
        ("Batch Capacity", "Process 100+ files efficiently"),
        ("Memory Usage", "<4GB peak memory usage"),
        ("Cost", "<$0.01 per transcript"),
        ("Code Coverage", ">80% with real file testing"),
        ("CLI Response", "<1 second CLI response time"),
        ("File Size", "Handle files up to 500MB"),
        ("Data Loss", "Zero data loss on errors"),
    ]

    for metric, target in metrics:
        print(f"  • {metric}: {target}")


def main():
    """Run the complete demo."""
    try:
        demo_agent_capabilities()
        demo_tool_details()
        demo_phase_progression()
        demo_development_workflow()
        demo_success_metrics()

        print("\n🎉 Demo Complete!")
        print("The backend developer agent is ready to build the Trax platform!")

    except Exception as e:
        print(f"Error running demo: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
