"""sageLLM Core 运行时。

本包提供 sageLLM 的核心运行时组件：
- LLMEngine: 统一的硬件无关推理引擎
- EngineCore: 协调 Scheduler 和 Executor
- Scheduler: Continuous Batching 调度器
- Executor: 管理 Worker 执行
- Worker/ModelRunner: 模型前向传播
- 配置 schema 与校验
- Engine 工厂函数
- 插件系统
- Demo Runner
- 分布式 Runtime（PD 分离 MVP）
- PD 分离执行器

Architecture:
    LLMEngine (hardware-agnostic)
        ├── EngineCore (coordinates Scheduler and Executor)
        │       └── Scheduler (Continuous Batching)
        └── Executor
                └── Worker
                        └── ModelRunner
                                ├── uses BackendProvider (from sagellm-backend)
                                └── uses CommBackend (from sagellm-comm)
"""

from __future__ import annotations

from sagellm_core._version import __version__

# ============================================================================
# Hardware-agnostic reference runtime architecture
# ============================================================================
from sagellm_core.llm_engine import LLMEngine, LLMEngineConfig
from sagellm_core.engine_core import EngineCore
from sagellm_core.engine_core.engine_core import EngineCoreConfig
from sagellm_core.engine_core.scheduler import (
    ContinuousBatchingScheduler,
    SchedulerConfig,
    SchedulerOutput,
)
from sagellm_core.executor import ExecutorBase, UniprocExecutor
from sagellm_core.executor.executor_base import ExecutorConfig
from sagellm_core.worker import Worker
from sagellm_core.worker.model_runner import ModelRunner
from sagellm_core.runtime_optimizer import (
    AdaptivePrecisionStrategy,
    BaseStrategy,
    CUDAGraphCaptureStrategy,
    DynamicBatchingStrategy,
    RuntimeOptimizer,
    RuntimeStats,
)

from sagellm_core.config import (
    BackendConfig,
    DemoConfig,
    EngineConfig,
    OutputConfig,
    WorkloadConfig,
    WorkloadSegment,
    load_config,
    merge_configs,
    validate_config_strict,
)
from sagellm_core.demo import main as demo_main
from sagellm_core.health import HealthStatus
from sagellm_core.plugins import PluginResolutionError, list_entry_points, resolve_kind

# P2 Plugin System (issues #72 #73 #74 #76 #64)
from sagellm_core.plugin import (
    AcceleratorPlugin,
    AcceleratorPluginMeta,
    BackendPlugin,
    BackendPluginMeta,
    EnginePlugin,
    EnginePluginMeta,
    PluginChain,
    PluginChainConfig,
    PluginRegistry,
    PluginRegistrySnapshot,
    SchedulerPlugin,
    SchedulerPluginMeta,
)
from sagellm_core.plugin.compression_bridge import (
    KernelFusionAcceleratorPlugin,
    QuantizationAcceleratorPlugin,
    SpeculativeAcceleratorPlugin,
)
from sagellm_core.runner import DemoRunner, RunnerContext
from sagellm_core.factory import create_backend, create_engine

# PD 分离 MVP 模块
from sagellm_core.runtime import DistributedConfig, DistributedRuntime, RuntimeState
from sagellm_core.pd_executor import PDExecutionContext, PDSeparatedExecutor

# PD 分离独立引擎（两个独立 Engine + KV via sagellm-comm）
from sagellm_core.pd import (
    KVTransferChannel,
    PrefillEngine,
    PrefillResult,
    DecodeEngine,
    DecodeResult,
)

# Engine HTTP Server
from sagellm_core.engine_server import app as engine_server_app
from sagellm_core.engine_server import main as serve_engine

# ============================================================================
# Phase 2: New Modules (P2 Priority)
# ============================================================================
# Model loading utilities
from sagellm_core.model import ModelLoader, load_model

# Input processing
from sagellm_core.inputs import InputProcessor, ProcessedInput, TokenizerWrapper

# Sampling utilities
from sagellm_core.sampling import SamplingParams, Sampler, GreedySampler

# Distributed strategies
from sagellm_core.distributed import DistributedStrategy, TensorParallelStrategy

# Observability
from sagellm_core.observability import MetricsCollector, EngineMetrics, setup_logger

__all__ = [
    # Version
    "__version__",
    # =========================================================================
    # Hardware-agnostic runtime architecture - RECOMMENDED
    # =========================================================================
    # LLMEngine - Unified hardware-agnostic engine
    "LLMEngine",
    "LLMEngineConfig",
    # EngineCore - Coordinates Scheduler and Executor
    "EngineCore",
    "EngineCoreConfig",
    # Scheduler - Continuous Batching
    "ContinuousBatchingScheduler",
    "SchedulerConfig",
    "SchedulerOutput",
    # Executor - Manages Workers
    "ExecutorBase",
    "ExecutorConfig",
    "UniprocExecutor",
    # Worker - Model execution
    "Worker",
    "ModelRunner",
    "AdaptivePrecisionStrategy",
    "BaseStrategy",
    "CUDAGraphCaptureStrategy",
    "DynamicBatchingStrategy",
    "RuntimeOptimizer",
    "RuntimeStats",
    # =========================================================================
    # Configuration (for YAML/config files)
    # =========================================================================
    "BackendConfig",
    "DemoConfig",
    "EngineConfig",
    "OutputConfig",
    "WorkloadConfig",
    "WorkloadSegment",
    "load_config",
    "merge_configs",
    "validate_config_strict",
    # Health status
    "HealthStatus",
    # Plugin system (legacy)
    "PluginResolutionError",
    "list_entry_points",
    "resolve_kind",
    # Plugin system P2 (issues #72 #73 #74 #76)
    "BackendPlugin",
    "BackendPluginMeta",
    "EnginePlugin",
    "EnginePluginMeta",
    "SchedulerPlugin",
    "SchedulerPluginMeta",
    "AcceleratorPlugin",
    "AcceleratorPluginMeta",
    "PluginRegistry",
    "PluginRegistrySnapshot",
    "PluginChain",
    "PluginChainConfig",
    # Compression bridge accelerator plugins
    "QuantizationAcceleratorPlugin",
    "KernelFusionAcceleratorPlugin",
    "SpeculativeAcceleratorPlugin",
    # Demo runner
    "demo_main",
    "DemoRunner",
    "RunnerContext",
    # Factory functions
    "create_backend",
    "create_engine",
    # PD Separation MVP
    "DistributedConfig",
    "DistributedRuntime",
    "RuntimeState",
    "PDExecutionContext",
    "PDSeparatedExecutor",
    # PD 分离独立引擎（Two-Engine PD Separation）
    "KVTransferChannel",
    "PrefillEngine",
    "PrefillResult",
    "DecodeEngine",
    "DecodeResult",
    # Engine HTTP Server
    "engine_server_app",
    "serve_engine",
    # Phase 2 modules
    "ModelLoader",
    "load_model",
    "InputProcessor",
    "ProcessedInput",
    "TokenizerWrapper",
    "SamplingParams",
    "Sampler",
    "GreedySampler",
    "DistributedStrategy",
    "TensorParallelStrategy",
    "MetricsCollector",
    "EngineMetrics",
    "setup_logger",
]
