"""
Default Pipeline.
[AC-AISVC-RES-01] 默认策略 Pipeline，复用现有逻辑。
"""

import logging
import time
from typing import Any

from app.services.retrieval.base import RetrievalContext, RetrievalResult
from app.services.retrieval.optimized_retriever import OptimizedRetriever, get_optimized_retriever
from app.services.retrieval.strategy.config import PipelineConfig
from app.services.retrieval.strategy.pipeline_base import (
    BasePipeline,
    PipelineContext,
    PipelineResult,
)

logger = logging.getLogger(__name__)


class DefaultPipeline(BasePipeline):
    """
    默认策略 Pipeline。【AC-AISVC-RES-01】
    
    复用现有 OptimizedRetriever 逻辑，保持线上行为不变。
    """
    
    def __init__(
        self,
        config: PipelineConfig | None = None,
        optimized_retriever: OptimizedRetriever | None = None,
    ):
        self._config = config or PipelineConfig()
        self._optimized_retriever = optimized_retriever
    
    @property
    def name(self) -> str:
        return "default_pipeline"
    
    @property
    def description(self) -> str:
        return "默认检索策略，复用现有 OptimizedRetriever 逻辑。"
    
    async def _get_retriever(self) -> OptimizedRetriever:
        if self._optimized_retriever is None:
            self._optimized_retriever = await get_optimized_retriever()
        return self._optimized_retriever
    
    async def retrieve(self, ctx: PipelineContext) -> PipelineResult:
        """执行默认检索流程。【AC-AISVC-RES-01】"""
        start_time = time.time()
        
        logger.info(
            f"[DefaultPipeline] Starting retrieval: tenant={ctx.tenant_id}, "
            f"query={ctx.query[:50]}..."
        )
        
        try:
            retriever = await self._get_retriever()
            
            metadata_filter = None
            if ctx.metadata_filter:
                metadata_filter = ctx.metadata_filter.filter_dict
            
            retrieval_ctx = RetrievalContext(
                tenant_id=ctx.tenant_id,
                query=ctx.query,
                session_id=ctx.session_id,
                metadata_filter=metadata_filter,
                kb_ids=ctx.kb_ids,
            )
            
            result = await retriever.retrieve(retrieval_ctx)
            
            latency_ms = (time.time() - start_time) * 1000
            
            logger.info(
                f"[DefaultPipeline] Retrieval completed: hits={len(result.hits)}, "
                f"latency_ms={latency_ms:.2f}"
            )
            
            return PipelineResult(
                retrieval_result=result,
                pipeline_name=self.name,
                metadata_filter_applied=metadata_filter is not None,
                latency_ms=latency_ms,
                diagnostics={
                    "retriever": "OptimizedRetriever",
                    **(result.diagnostics or {}),
                },
            )
            
        except Exception as e:
            latency_ms = (time.time() - start_time) * 1000
            logger.error(f"[DefaultPipeline] Retrieval error: {e}", exc_info=True)
            return self._create_empty_result(ctx, error=str(e), latency_ms=latency_ms)
    
    async def health_check(self) -> bool:
        """健康检查。"""
        try:
            retriever = await self._get_retriever()
            return await retriever.health_check()
        except Exception as e:
            logger.error(f"[DefaultPipeline] Health check failed: {e}")
            return False


_default_pipeline: DefaultPipeline | None = None


async def get_default_pipeline() -> DefaultPipeline:
    """获取 DefaultPipeline 单例。"""
    global _default_pipeline
    if _default_pipeline is None:
        _default_pipeline = DefaultPipeline()
    return _default_pipeline
