"""Backend Developer Tools and Capabilities.

This module defines the specific tools, commands, and capabilities that the backend developer
agent can use for building the Trax media processing platform.
"""

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


class ToolPermission(Enum):
    """Permission levels for tools."""

    READ_ONLY = "read_only"
    EXECUTE = "execute"
    MODIFY = "modify"
    ADMIN = "admin"


@dataclass
class ToolCapability:
    """Defines a specific capability of a tool."""

    name: str
    description: str
    command: str
    permission: ToolPermission
    examples: List[str]


@dataclass
class DeveloperTool:
    """Complete tool definition for backend developer."""

    name: str
    category: str
    description: str
    capabilities: List[ToolCapability]
    required_skills: List[str]
    phase_availability: List[str]  # Which development phases can use this tool


# Core Development Tools
PYTHON_DEVELOPMENT = DeveloperTool(
    name="Python 3.11+ Development",
    category="core_development",
    description="Core Python development with async/await patterns",
    capabilities=[
        ToolCapability(
            name="Async Programming",
            description="Write async/await code for concurrent operations",
            command="async def transcribe_audio(audio_path: Path) -> Transcript:",
            permission=ToolPermission.MODIFY,
            examples=[
                "async def process_batch(files: List[Path]):",
                "await asyncio.gather(*[process_file(f) for f in files])",
                "async with aiofiles.open(file_path) as f:",
            ],
        ),
        ToolCapability(
            name="Protocol Design",
            description="Create protocol-based service interfaces",
            command="class TranscriptionService(Protocol):",
            permission=ToolPermission.MODIFY,
            examples=[
                "class TranscriptionService(Protocol):",
                "    async def transcribe(self, audio: Path) -> Transcript: ...",
                "    def can_handle(self, audio: Path) -> bool: ...",
            ],
        ),
        ToolCapability(
            name="Type Hints",
            description="Use comprehensive type hints throughout",
            command="def process_audio(audio: Path) -> Optional[Transcript]:",
            permission=ToolPermission.MODIFY,
            examples=[
                "from typing import Protocol, List, Dict, Optional",
                "def create_transcript(segments: List[Segment]) -> Transcript:",
                "async def get_enhanced_text(text: str) -> EnhancedText:",
            ],
        ),
    ],
    required_skills=["Python 3.11+", "async/await", "Protocol patterns", "type hints"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

UV_PACKAGE_MANAGER = DeveloperTool(
    name="uv Package Manager",
    category="core_development",
    description="Ultra-fast Python package manager",
    capabilities=[
        ToolCapability(
            name="Install Dependencies",
            description="Install project dependencies",
            command="uv pip install -e .",
            permission=ToolPermission.EXECUTE,
            examples=[
                "uv pip install faster-whisper",
                "uv pip install -e .[dev]",
                "uv pip install --upgrade package-name",
            ],
        ),
        ToolCapability(
            name="Compile Requirements",
            description="Generate requirements.txt from pyproject.toml",
            command="uv pip compile pyproject.toml -o requirements.txt",
            permission=ToolPermission.EXECUTE,
            examples=[
                "uv pip compile pyproject.toml",
                "uv pip compile pyproject.toml --extra dev",
                "uv pip compile pyproject.toml --upgrade",
            ],
        ),
        ToolCapability(
            name="Run Commands",
            description="Execute Python commands with uv",
            command="uv run python src/main.py",
            permission=ToolPermission.EXECUTE,
            examples=["uv run pytest", "uv run python -m src.cli.main", "uv run mypy src/"],
        ),
    ],
    required_skills=["uv", "dependency management", "Python packaging"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

# Database Tools
POSTGRESQL_SQLALCHEMY = DeveloperTool(
    name="PostgreSQL + SQLAlchemy",
    category="database",
    description="Database schema design with JSONB",
    capabilities=[
        ToolCapability(
            name="Model Definition",
            description="Define SQLAlchemy models with JSONB",
            command="class Transcript(Base):",
            permission=ToolPermission.MODIFY,
            examples=[
                "class Transcript(Base):",
                "    __tablename__ = 'transcripts'",
                "    id = Column(Integer, primary_key=True)",
                "    content = Column(JSONB, nullable=False)",
                "    metadata = Column(JSONB, default={})",
            ],
        ),
        ToolCapability(
            name="Database Migrations",
            description="Create and apply Alembic migrations",
            command="alembic revision -m 'Add transcript table'",
            permission=ToolPermission.EXECUTE,
            examples=[
                "alembic revision -m 'description'",
                "alembic upgrade head",
                "alembic downgrade -1",
            ],
        ),
        ToolCapability(
            name="JSONB Operations",
            description="Perform JSONB queries and operations",
            command="session.query(Transcript).filter(Transcript.content['segments'].astext.contains('text'))",
            permission=ToolPermission.MODIFY,
            examples=[
                "Transcript.content['segments'].astext.contains('search_term')",
                "func.jsonb_extract_path(Transcript.content, 'segments')",
                "Transcript.metadata['version'].astext == 'v1'",
            ],
        ),
    ],
    required_skills=["PostgreSQL", "SQLAlchemy", "JSONB", "Alembic"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

# ML Integration Tools
WHISPER_INTEGRATION = DeveloperTool(
    name="Whisper Integration",
    category="ml_integration",
    description="OpenAI Whisper model integration",
    capabilities=[
        ToolCapability(
            name="Model Loading",
            description="Load Whisper models with faster-whisper",
            command="from faster_whisper import WhisperModel",
            permission=ToolPermission.MODIFY,
            examples=[
                "model = WhisperModel('distil-large-v3', device='mps')",
                "model = WhisperModel('base', compute_type='int8')",
                "model = WhisperModel('large-v3', device='cpu')",
            ],
        ),
        ToolCapability(
            name="Audio Transcription",
            description="Transcribe audio files with Whisper",
            command="segments, info = model.transcribe(audio_path)",
            permission=ToolPermission.MODIFY,
            examples=[
                "segments, info = model.transcribe('audio.wav')",
                "for segment in segments:",
                "    print(f'{segment.start:.2f}s - {segment.text}')",
            ],
        ),
        ToolCapability(
            name="Chunking Strategy",
            description="Handle large audio files with chunking",
            command="model.transcribe(audio_path, chunk_length=30)",
            permission=ToolPermission.MODIFY,
            examples=[
                "model.transcribe(audio_path, chunk_length=30, overlap=2)",
                "model.transcribe(audio_path, beam_size=5)",
                "model.transcribe(audio_path, language='en')",
            ],
        ),
    ],
    required_skills=["Whisper", "faster-whisper", "ML integration", "audio processing"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

# Testing Tools
PYTEST_REAL_FILES = DeveloperTool(
    name="pytest with Real Files",
    category="testing",
    description="Testing with actual audio files (no mocks)",
    capabilities=[
        ToolCapability(
            name="Real File Testing",
            description="Test with actual audio files instead of mocks",
            command="uv run pytest tests/",
            permission=ToolPermission.EXECUTE,
            examples=[
                "def test_transcribe_real_audio(audio_file: Path):",
                "    result = transcription_service.transcribe(audio_file)",
                "    assert result is not None",
                "    assert len(result.segments) > 0",
            ],
        ),
        ToolCapability(
            name="Test Fixtures",
            description="Create reusable test fixtures with real files",
            command="@pytest.fixture",
            permission=ToolPermission.MODIFY,
            examples=[
                "@pytest.fixture",
                "def sample_audio_file() -> Path:",
                "    return Path('tests/fixtures/sample_audio.wav')",
                "",
                "@pytest.fixture",
                "def transcription_service() -> TranscriptionService:",
                "    return WhisperTranscriptionService()",
            ],
        ),
        ToolCapability(
            name="Performance Testing",
            description="Benchmark transcription performance",
            command="uv run pytest tests/test_performance.py",
            permission=ToolPermission.EXECUTE,
            examples=[
                "def test_transcription_speed(benchmark, audio_file):",
                "    result = benchmark(transcribe_audio, audio_file)",
                "    assert result.duration < 30.0  # 30 seconds for 5min audio",
            ],
        ),
    ],
    required_skills=["pytest", "real file testing", "factory patterns", "benchmarking"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

# Architecture Tools
ITERATIVE_PIPELINE = DeveloperTool(
    name="Iterative Pipeline Design",
    category="architecture",
    description="Version-based pipeline (v1→v2→v3→v4)",
    capabilities=[
        ToolCapability(
            name="Version Management",
            description="Manage different pipeline versions",
            command="class PipelineManager:",
            permission=ToolPermission.MODIFY,
            examples=[
                "class PipelineManager:",
                "    def __init__(self, version: str = 'v1'):",
                "        self.version = version",
                "        self.services = self._load_services()",
                "",
                "    def _load_services(self) -> Dict[str, TranscriptionService]:",
                "        if self.version == 'v1':",
                "            return {'whisper': WhisperService()}",
                "        elif self.version == 'v2':",
                "            return {'whisper': WhisperService(), 'enhance': DeepSeekService()}",
            ],
        ),
        ToolCapability(
            name="Backward Compatibility",
            description="Ensure new versions work with old data",
            command="def migrate_transcript(transcript: Transcript, target_version: str) -> Transcript:",
            permission=ToolPermission.MODIFY,
            examples=[
                "def migrate_transcript(transcript: Transcript, target_version: str) -> Transcript:",
                "    if transcript.version == 'v1' and target_version == 'v2':",
                "        return enhance_transcript(transcript)",
                "    return transcript",
            ],
        ),
        ToolCapability(
            name="Feature Flags",
            description="Enable/disable features by version",
            command="if config.get('enable_enhancement', False):",
            permission=ToolPermission.MODIFY,
            examples=[
                "def should_enhance(version: str) -> bool:",
                "    return version in ['v2', 'v3', 'v4']",
                "",
                "if should_enhance(pipeline.version):",
                "    transcript = enhance_transcript(transcript)",
            ],
        ),
    ],
    required_skills=["version management", "backward compatibility", "feature flags"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

# Performance Tools
M3_OPTIMIZATION = DeveloperTool(
    name="M3 Hardware Optimization",
    category="performance",
    description="Optimize for Apple Silicon",
    capabilities=[
        ToolCapability(
            name="Metal Performance Shaders",
            description="Use M3 GPU for Whisper inference",
            command="model = WhisperModel('distil-large-v3', device='mps')",
            permission=ToolPermission.MODIFY,
            examples=[
                "import torch",
                "if torch.backends.mps.is_available():",
                "    device = 'mps'",
                "else:",
                "    device = 'cpu'",
                "",
                "model = WhisperModel('distil-large-v3', device=device)",
            ],
        ),
        ToolCapability(
            name="Memory Optimization",
            description="Optimize memory usage for large files",
            command="model.transcribe(audio_path, chunk_length=30, overlap=2)",
            permission=ToolPermission.MODIFY,
            examples=[
                "def transcribe_large_file(audio_path: Path) -> Transcript:",
                "    model = WhisperModel('distil-large-v3', device='mps')",
                "    segments, info = model.transcribe(",
                "        audio_path,",
                "        chunk_length=30,",
                "        overlap=2,",
                "        beam_size=1  # Reduce memory usage",
                "    )",
            ],
        ),
        ToolCapability(
            name="Performance Profiling",
            description="Profile and optimize performance",
            command="python -m cProfile -o profile.stats src/main.py",
            permission=ToolPermission.EXECUTE,
            examples=[
                "import cProfile",
                "import pstats",
                "",
                "profiler = cProfile.Profile()",
                "profiler.enable()",
                "transcribe_audio(audio_file)",
                "profiler.disable()",
                "stats = pstats.Stats(profiler)",
                "stats.sort_stats('cumulative').print_stats(10)",
            ],
        ),
    ],
    required_skills=["Apple Silicon", "Metal Performance Shaders", "performance profiling"],
    phase_availability=["v1", "v2", "v3", "v4"],
)

# All available tools
BACKEND_DEVELOPER_TOOLS = [
    PYTHON_DEVELOPMENT,
    UV_PACKAGE_MANAGER,
    POSTGRESQL_SQLALCHEMY,
    WHISPER_INTEGRATION,
    PYTEST_REAL_FILES,
    ITERATIVE_PIPELINE,
    M3_OPTIMIZATION,
]


def get_tools_by_category(category: str) -> List[DeveloperTool]:
    """Get all tools in a specific category."""
    return [tool for tool in BACKEND_DEVELOPER_TOOLS if tool.category == category]


def get_tools_by_phase(phase: str) -> List[DeveloperTool]:
    """Get all tools available in a specific development phase."""
    return [tool for tool in BACKEND_DEVELOPER_TOOLS if phase in tool.phase_availability]


def get_tool_by_name(name: str) -> Optional[DeveloperTool]:
    """Get a specific tool by name."""
    for tool in BACKEND_DEVELOPER_TOOLS:
        if tool.name.lower() == name.lower():
            return tool
    return None


def list_all_capabilities() -> Dict[str, List[str]]:
    """List all capabilities by tool."""
    capabilities = {}
    for tool in BACKEND_DEVELOPER_TOOLS:
        capabilities[tool.name] = [cap.name for cap in tool.capabilities]
    return capabilities


def get_required_skills() -> List[str]:
    """Get all required skills across all tools."""
    skills = set()
    for tool in BACKEND_DEVELOPER_TOOLS:
        skills.update(tool.required_skills)
    return sorted(list(skills))


if __name__ == "__main__":
    # Example usage
    print("Backend Developer Tools and Capabilities")
    print("=" * 50)

    for tool in BACKEND_DEVELOPER_TOOLS:
        print(f"\n{tool.name}")
        print(f"Category: {tool.category}")
        print(f"Description: {tool.description}")
        print(f"Available in phases: {', '.join(tool.phase_availability)}")
        print("Capabilities:")
        for cap in tool.capabilities:
            print(f"  - {cap.name}: {cap.description}")
        print(f"Required skills: {', '.join(tool.required_skills)}")

    print(f"\nTotal tools: {len(BACKEND_DEVELOPER_TOOLS)}")
    print(f"Total required skills: {len(get_required_skills())}")

    print("\nTools by category:")
    categories = set(tool.category for tool in BACKEND_DEVELOPER_TOOLS)
    for category in sorted(categories):
        tools = get_tools_by_category(category)
        print(f"  {category}: {len(tools)} tools")
