"""
Strategic Pipeline Registry.

Provides intelligent defaults for LLM assistance across key operational pipelines.
Ported from aperion-legendary-ai with enhancements.
"""

from __future__ import annotations

from enum import Enum
from typing import Any

from pydantic import BaseModel, Field

from aperion_flow.definitions.pipeline import LLMAssistanceConfig, LLMAssistanceMode


class PipelineCategory(str, Enum):
    """Strategic pipeline categories."""

    TESTING = "testing"
    DEPLOYMENT = "deployment"
    MONITORING = "monitoring"
    CODE_ANALYSIS = "code_analysis"
    DATA_PROCESSING = "data_processing"
    REPORTING = "reporting"
    MAINTENANCE = "maintenance"
    INTEGRATION = "integration"


class StrategicPipelineConfig(BaseModel):
    """Configuration for a strategic pipeline with recommended LLM assistance."""

    name: str
    category: PipelineCategory
    description: str
    recommended_modes: list[LLMAssistanceMode]
    default_timeout: float = Field(default=10.0, gt=0.0)
    cache_enabled: bool = True
    fallback_on_error: bool = True
    priority: int = Field(default=5, ge=1, le=10)  # Higher = more critical
    metadata: dict[str, Any] = Field(default_factory=dict)

    model_config = {"frozen": True}


class StrategicPipelineRegistry:
    """
    Registry of strategic pipelines with intelligent LLM assistance defaults.

    Provides sensible defaults while allowing opt-out or customization.
    """

    def __init__(self) -> None:
        """Initialize the registry."""
        self._pipelines: dict[str, StrategicPipelineConfig] = {}
        self._register_defaults()

    def _register_defaults(self) -> None:
        """Register default strategic pipelines."""

        # TESTING PIPELINES
        self.register(StrategicPipelineConfig(
            name="pytest_execution",
            category=PipelineCategory.TESTING,
            description="Execute pytest test suites with intelligent failure diagnosis",
            recommended_modes=[
                LLMAssistanceMode.PRE_VALIDATE,
                LLMAssistanceMode.ERROR_DIAGNOSIS,
            ],
            priority=9,
            metadata={
                "use_cases": ["unit tests", "integration tests", "e2e tests"],
                "benefits": ["faster debugging", "root cause analysis"],
            },
        ))

        self.register(StrategicPipelineConfig(
            name="coverage_analysis",
            category=PipelineCategory.TESTING,
            description="Analyze test coverage and identify gaps",
            recommended_modes=[
                LLMAssistanceMode.ANALYZE_OUTPUT,
                LLMAssistanceMode.ENRICH_CONTEXT,
            ],
            priority=7,
            metadata={
                "coverage_threshold": 0.95,
                "focus_areas": ["critical paths"],
            },
        ))

        # DEPLOYMENT PIPELINES
        self.register(StrategicPipelineConfig(
            name="pre_deployment_validation",
            category=PipelineCategory.DEPLOYMENT,
            description="Validate configurations, dependencies, and environment before deploy",
            recommended_modes=[
                LLMAssistanceMode.PRE_VALIDATE,
                LLMAssistanceMode.ENRICH_CONTEXT,
            ],
            priority=10,
            metadata={
                "checks": ["config validation", "dependency compatibility", "env vars"],
                "blocking": True,
            },
        ))

        self.register(StrategicPipelineConfig(
            name="post_deployment_health",
            category=PipelineCategory.DEPLOYMENT,
            description="Verify system health after deployment",
            recommended_modes=[
                LLMAssistanceMode.ANALYZE_OUTPUT,
                LLMAssistanceMode.ERROR_DIAGNOSIS,
            ],
            priority=10,
            metadata={"health_endpoints": ["/healthz", "/readyz"]},
        ))

        # MONITORING PIPELINES
        self.register(StrategicPipelineConfig(
            name="metrics_analysis",
            category=PipelineCategory.MONITORING,
            description="Analyze system metrics and detect anomalies",
            recommended_modes=[
                LLMAssistanceMode.ANALYZE_OUTPUT,
                LLMAssistanceMode.ENRICH_CONTEXT,
            ],
            priority=8,
            metadata={
                "metrics": ["response_time", "error_rate", "throughput"],
                "baseline_window": "7d",
            },
        ))

        self.register(StrategicPipelineConfig(
            name="alert_enrichment",
            category=PipelineCategory.MONITORING,
            description="Enrich alerts with context and recommended actions",
            recommended_modes=[
                LLMAssistanceMode.ENRICH_CONTEXT,
                LLMAssistanceMode.ERROR_DIAGNOSIS,
            ],
            priority=9,
        ))

        # CODE ANALYSIS PIPELINES
        self.register(StrategicPipelineConfig(
            name="lint_diagnosis",
            category=PipelineCategory.CODE_ANALYSIS,
            description="Diagnose linting errors with intelligent recommendations",
            recommended_modes=[
                LLMAssistanceMode.ERROR_DIAGNOSIS,
                LLMAssistanceMode.ENRICH_CONTEXT,
            ],
            priority=6,
            metadata={
                "linters": ["ruff", "black", "flake8", "bandit"],
                "auto_fix": False,
            },
        ))

        self.register(StrategicPipelineConfig(
            name="security_scan",
            category=PipelineCategory.CODE_ANALYSIS,
            description="Scan code for security vulnerabilities",
            recommended_modes=[
                LLMAssistanceMode.PRE_VALIDATE,
                LLMAssistanceMode.ANALYZE_OUTPUT,
            ],
            priority=10,
            metadata={
                "scanners": ["bandit", "semgrep", "trivy"],
                "severity_threshold": "medium",
            },
        ))

        # DATA PROCESSING PIPELINES
        self.register(StrategicPipelineConfig(
            name="data_validation",
            category=PipelineCategory.DATA_PROCESSING,
            description="Validate data quality and schema compliance",
            recommended_modes=[
                LLMAssistanceMode.PRE_VALIDATE,
                LLMAssistanceMode.ERROR_DIAGNOSIS,
            ],
            priority=8,
        ))

        # REPORTING PIPELINES
        self.register(StrategicPipelineConfig(
            name="report_generation",
            category=PipelineCategory.REPORTING,
            description="Generate intelligent reports with insights",
            recommended_modes=[
                LLMAssistanceMode.ENRICH_CONTEXT,
                LLMAssistanceMode.ANALYZE_OUTPUT,
            ],
            priority=5,
        ))

        # MAINTENANCE PIPELINES
        self.register(StrategicPipelineConfig(
            name="database_maintenance",
            category=PipelineCategory.MAINTENANCE,
            description="Perform database maintenance and optimization",
            recommended_modes=[
                LLMAssistanceMode.PRE_VALIDATE,
                LLMAssistanceMode.ANALYZE_OUTPUT,
            ],
            priority=7,
        ))

        # INTEGRATION PIPELINES
        self.register(StrategicPipelineConfig(
            name="api_integration",
            category=PipelineCategory.INTEGRATION,
            description="Integrate with external APIs and handle data sync",
            recommended_modes=[
                LLMAssistanceMode.PRE_VALIDATE,
                LLMAssistanceMode.ERROR_DIAGNOSIS,
            ],
            priority=8,
            metadata={"retry_strategy": "exponential_backoff"},
        ))

    def register(self, config: StrategicPipelineConfig) -> None:
        """Register a strategic pipeline configuration."""
        self._pipelines[config.name] = config

    def get(self, name: str) -> StrategicPipelineConfig | None:
        """Get configuration for a strategic pipeline."""
        return self._pipelines.get(name)

    def get_by_category(self, category: PipelineCategory) -> list[StrategicPipelineConfig]:
        """Get all pipelines in a category."""
        return [cfg for cfg in self._pipelines.values() if cfg.category == category]

    def list_all(self) -> list[StrategicPipelineConfig]:
        """List all registered strategic pipelines."""
        return list(self._pipelines.values())

    def get_llm_config(
        self,
        pipeline_name: str,
        mode: LLMAssistanceMode,
        enabled: bool = True,
        **kwargs: Any,
    ) -> LLMAssistanceConfig:
        """
        Get LLM assistance configuration for a pipeline stage.

        Args:
            pipeline_name: Name of the strategic pipeline
            mode: LLM assistance mode to use
            enabled: Whether LLM assistance is enabled
            **kwargs: Override default configuration

        Returns:
            LLM assistance configuration with intelligent defaults
        """
        config = self.get(pipeline_name)

        # Default configuration
        defaults: dict[str, Any] = {
            "timeout": 10.0,
            "cache_results": True,
            "fallback_on_error": True,
        }

        # Apply strategic defaults if available
        if config:
            defaults["timeout"] = config.default_timeout
            defaults["cache_results"] = config.cache_enabled
            defaults["fallback_on_error"] = config.fallback_on_error

            # Add pipeline metadata
            metadata = kwargs.pop("metadata", {})
            if config.metadata:
                metadata.update(config.metadata)
            metadata["pipeline_name"] = pipeline_name
            metadata["category"] = config.category.value
            metadata["priority"] = config.priority
            kwargs["metadata"] = metadata

        # Apply user overrides
        timeout = kwargs.pop("timeout", defaults["timeout"])
        cache_results = kwargs.pop("cache_results", defaults["cache_results"])
        fallback_on_error = kwargs.pop("fallback_on_error", defaults["fallback_on_error"])

        return LLMAssistanceConfig(
            mode=mode,
            enabled=enabled,
            timeout=timeout,
            cache_results=cache_results,
            fallback_on_error=fallback_on_error,
            **kwargs,
        )

    def is_strategic(self, pipeline_name: str) -> bool:
        """Check if a pipeline is strategic (has default LLM config)."""
        return pipeline_name in self._pipelines

    def get_recommended_modes(self, pipeline_name: str) -> list[LLMAssistanceMode]:
        """Get recommended LLM assistance modes for a pipeline."""
        config = self.get(pipeline_name)
        return config.recommended_modes if config else []

    def get_statistics(self) -> dict[str, Any]:
        """Get registry statistics."""
        total = len(self._pipelines)
        by_category: dict[str, int] = {}
        by_priority: dict[str, int] = {}

        for config in self._pipelines.values():
            # Count by category
            cat = config.category.value
            by_category[cat] = by_category.get(cat, 0) + 1

            # Count by priority range
            priority_range = f"{(config.priority // 3) * 3 + 1}-{(config.priority // 3) * 3 + 3}"
            by_priority[priority_range] = by_priority.get(priority_range, 0) + 1

        return {
            "total_pipelines": total,
            "by_category": by_category,
            "by_priority": by_priority,
            "categories": [cat.value for cat in PipelineCategory],
            "assistance_modes": [mode.value for mode in LLMAssistanceMode],
        }


# Global registry instance
_registry: StrategicPipelineRegistry | None = None


def get_registry() -> StrategicPipelineRegistry:
    """Get the global strategic pipeline registry."""
    global _registry
    if _registry is None:
        _registry = StrategicPipelineRegistry()
    return _registry
