"""Backend Python Developer Agent for Trax Media Processing Platform.

This agent represents the first backend developer hire, with specific tools and capabilities
for building the protocol-based transcription pipeline.
"""

from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List


class ToolCategory(Enum):
    """Categories of tools the backend developer can use."""

    CORE_DEVELOPMENT = "core_development"
    DATABASE = "database"
    ML_INTEGRATION = "ml_integration"
    TESTING = "testing"
    ARCHITECTURE = "architecture"
    PERFORMANCE = "performance"
    DEPLOYMENT = "deployment"


@dataclass
class DeveloperTool:
    """Represents a tool the backend developer can use."""

    name: str
    category: ToolCategory
    description: str
    command: str
    required_skills: List[str]
    usage_examples: List[str]


class BackendDeveloperAgent:
    """Agent representing the first backend Python developer for Trax.

    This agent has access to specific tools and capabilities needed to build
    the protocol-based transcription pipeline from v1 to v4.
    """

    def __init__(self):
        self.name = "Backend Python Developer"
        self.role = "Senior Backend Developer"
        self.experience_level = "Senior"
        self.salary_range = "$150,000 - $200,000"
        self.available_tools = self._initialize_tools()
        self.current_focus = "Phase 1: Foundation (Weeks 1-2)"

    def _initialize_tools(self) -> Dict[ToolCategory, List[DeveloperTool]]:
        """Initialize all tools the backend developer can use."""
        tools = {
            ToolCategory.CORE_DEVELOPMENT: [
                DeveloperTool(
                    name="Python 3.11+ Development",
                    category=ToolCategory.CORE_DEVELOPMENT,
                    description="Core Python development with async/await patterns",
                    command="python src/main.py",
                    required_skills=["Python 3.11+", "async/await", "Protocol patterns"],
                    usage_examples=[
                        "Implement protocol-based transcription services",
                        "Build async batch processing pipelines",
                        "Create CLI interfaces with Click",
                    ],
                ),
                DeveloperTool(
                    name="uv Package Manager",
                    category=ToolCategory.CORE_DEVELOPMENT,
                    description="Ultra-fast Python package manager",
                    command="uv pip install -e .",
                    required_skills=["uv", "dependency management"],
                    usage_examples=[
                        "Install project dependencies",
                        "Manage development environment",
                        "Compile requirements.txt",
                    ],
                ),
                DeveloperTool(
                    name="Click CLI Framework",
                    category=ToolCategory.CORE_DEVELOPMENT,
                    description="Command-line interface creation",
                    command="trax transcribe video.mp4",
                    required_skills=["Click", "CLI design"],
                    usage_examples=[
                        "Create transcription commands",
                        "Build batch processing interface",
                        "Implement export functionality",
                    ],
                ),
            ],
            ToolCategory.DATABASE: [
                DeveloperTool(
                    name="PostgreSQL + SQLAlchemy",
                    category=ToolCategory.DATABASE,
                    description="Database schema design with JSONB",
                    command="alembic upgrade head",
                    required_skills=["PostgreSQL", "SQLAlchemy", "JSONB", "Alembic"],
                    usage_examples=[
                        "Design transcript storage schema",
                        "Implement JSONB for flexible data",
                        "Create database migrations",
                    ],
                ),
                DeveloperTool(
                    name="Database Registry Pattern",
                    category=ToolCategory.DATABASE,
                    description="Prevent SQLAlchemy multiple classes errors",
                    command="from src.database import registry",
                    required_skills=["SQLAlchemy patterns", "registry design"],
                    usage_examples=[
                        "Implement centralized model registry",
                        "Handle multiple database connections",
                        "Manage model relationships",
                    ],
                ),
            ],
            ToolCategory.ML_INTEGRATION: [
                DeveloperTool(
                    name="Whisper Integration",
                    category=ToolCategory.ML_INTEGRATION,
                    description="OpenAI Whisper model integration",
                    command="from faster_whisper import WhisperModel",
                    required_skills=["Whisper", "faster-whisper", "ML integration"],
                    usage_examples=[
                        "Integrate distil-large-v3 model",
                        "Optimize for M3 hardware",
                        "Implement chunking for large files",
                    ],
                ),
                DeveloperTool(
                    name="Protocol-Based Services",
                    category=ToolCategory.ML_INTEGRATION,
                    description="Clean service interfaces with protocols",
                    command="class TranscriptionService(Protocol):",
                    required_skills=["typing.Protocol", "dependency injection"],
                    usage_examples=[
                        "Design service interfaces",
                        "Implement version compatibility",
                        "Create swappable components",
                    ],
                ),
                DeveloperTool(
                    name="DeepSeek API Integration",
                    category=ToolCategory.ML_INTEGRATION,
                    description="AI enhancement for transcripts",
                    command="from src.services.deepseek import DeepSeekService",
                    required_skills=["API integration", "prompt engineering"],
                    usage_examples=[
                        "Enhance transcript quality",
                        "Implement structured outputs",
                        "Handle API rate limits",
                    ],
                ),
            ],
            ToolCategory.TESTING: [
                DeveloperTool(
                    name="pytest with Real Files",
                    category=ToolCategory.TESTING,
                    description="Testing with actual audio files (no mocks)",
                    command="uv run pytest tests/",
                    required_skills=["pytest", "real file testing", "factory patterns"],
                    usage_examples=[
                        "Test with actual audio files",
                        "Create test fixtures",
                        "Benchmark performance",
                    ],
                ),
                DeveloperTool(
                    name="Coverage Reporting",
                    category=ToolCategory.TESTING,
                    description="Code coverage analysis",
                    command="uv run pytest --cov=src",
                    required_skills=["coverage", "test quality"],
                    usage_examples=[
                        "Achieve >80% code coverage",
                        "Identify untested code",
                        "Track test quality",
                    ],
                ),
            ],
            ToolCategory.ARCHITECTURE: [
                DeveloperTool(
                    name="Iterative Pipeline Design",
                    category=ToolCategory.ARCHITECTURE,
                    description="Version-based pipeline (v1→v2→v3→v4)",
                    command="from src.pipeline import PipelineManager",
                    required_skills=["version management", "backward compatibility"],
                    usage_examples=[
                        "Design version transitions",
                        "Maintain backward compatibility",
                        "Implement feature flags",
                    ],
                ),
                DeveloperTool(
                    name="Batch Processing System",
                    category=ToolCategory.ARCHITECTURE,
                    description="Handle 100+ files efficiently",
                    command="trax batch /media/folder",
                    required_skills=["queue management", "parallel processing"],
                    usage_examples=[
                        "Process multiple files",
                        "Handle independent failures",
                        "Track progress",
                    ],
                ),
                DeveloperTool(
                    name="Caching Strategy",
                    category=ToolCategory.ARCHITECTURE,
                    description="Multi-layer caching with different TTLs",
                    command="from src.caching import CacheManager",
                    required_skills=["caching", "TTL management"],
                    usage_examples=[
                        "Cache expensive operations",
                        "Implement different TTLs",
                        "Handle cache invalidation",
                    ],
                ),
            ],
            ToolCategory.PERFORMANCE: [
                DeveloperTool(
                    name="Performance Profiling",
                    category=ToolCategory.PERFORMANCE,
                    description="Optimize processing speed and memory",
                    command="python -m cProfile src/main.py",
                    required_skills=["profiling", "optimization"],
                    usage_examples=[
                        "Profile transcription speed",
                        "Optimize memory usage",
                        "Benchmark improvements",
                    ],
                ),
                DeveloperTool(
                    name="M3 Hardware Optimization",
                    category=ToolCategory.PERFORMANCE,
                    description="Optimize for Apple Silicon",
                    command="whisper --device mps",
                    required_skills=["Apple Silicon", "Metal Performance Shaders"],
                    usage_examples=["Leverage M3 GPU", "Optimize for Metal", "Reduce CPU usage"],
                ),
            ],
            ToolCategory.DEPLOYMENT: [
                DeveloperTool(
                    name="Docker Containerization",
                    category=ToolCategory.DEPLOYMENT,
                    description="Containerize the application",
                    command="docker build -t trax .",
                    required_skills=["Docker", "containerization"],
                    usage_examples=[
                        "Create production images",
                        "Handle dependencies",
                        "Optimize image size",
                    ],
                ),
                DeveloperTool(
                    name="CI/CD Pipeline",
                    category=ToolCategory.DEPLOYMENT,
                    description="Automated testing and deployment",
                    command="github actions workflow",
                    required_skills=["CI/CD", "GitHub Actions"],
                    usage_examples=["Automate testing", "Deploy to staging", "Monitor deployments"],
                ),
            ],
        }
        return tools

    def get_tools_by_category(self, category: ToolCategory) -> List[DeveloperTool]:
        """Get all tools in a specific category."""
        return self.available_tools.get(category, [])

    def get_all_tools(self) -> List[DeveloperTool]:
        """Get all available tools."""
        all_tools = []
        for tools in self.available_tools.values():
            all_tools.extend(tools)
        return all_tools

    def can_use_tool(self, tool_name: str) -> bool:
        """Check if the developer can use a specific tool."""
        for tool in self.get_all_tools():
            if tool.name.lower() == tool_name.lower():
                return True
        return False

    def get_required_skills(self) -> List[str]:
        """Get all required skills for the role."""
        skills = set()
        for tool in self.get_all_tools():
            skills.update(tool.required_skills)
        return sorted(list(skills))

    def get_current_phase_tools(self) -> List[DeveloperTool]:
        """Get tools most relevant to current development phase."""
        if self.current_focus == "Phase 1: Foundation (Weeks 1-2)":
            # Focus on core development and database
            phase_tools = []
            phase_tools.extend(self.get_tools_by_category(ToolCategory.CORE_DEVELOPMENT))
            phase_tools.extend(self.get_tools_by_category(ToolCategory.DATABASE))
            phase_tools.extend(self.get_tools_by_category(ToolCategory.TESTING))
            return phase_tools
        # Add other phases as needed
        return self.get_all_tools()

    def execute_development_task(self, task: str) -> Dict[str, Any]:
        """Execute a development task using available tools."""
        # This would be implemented based on the specific task
        return {
            "task": task,
            "status": "executed",
            "tools_used": [],
            "output": "Task completed successfully",
        }


# Agent instance
backend_developer = BackendDeveloperAgent()


def get_backend_developer_agent() -> BackendDeveloperAgent:
    """Get the backend developer agent instance."""
    return backend_developer


def list_available_tools() -> Dict[str, List[str]]:
    """List all available tools by category."""
    agent = get_backend_developer_agent()
    tools_by_category = {}

    for category in ToolCategory:
        tools = agent.get_tools_by_category(category)
        tools_by_category[category.value] = [tool.name for tool in tools]

    return tools_by_category


def check_tool_availability(tool_name: str) -> bool:
    """Check if a specific tool is available."""
    agent = get_backend_developer_agent()
    return agent.can_use_tool(tool_name)


if __name__ == "__main__":
    # Example usage
    agent = get_backend_developer_agent()

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

    print("\nAvailable 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}")

    print(f"\nTotal Tools Available: {len(agent.get_all_tools())}")
    print(f"Required Skills: {len(agent.get_required_skills())}")
