"""CLI helper functions for backend resolution."""

from __future__ import annotations

import os
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from logos_adk.learning import LearningStore


def _build_learning_store(path: str | None) -> "LearningStore":
    """Build learning store from path or environment."""
    from logos_adk.learning import PostgreSQLLearningStore, SQLiteLearningStore

    backend = os.getenv("LOGOS_ADK_LEARNING_BACKEND", "").strip().lower()
    dsn = os.getenv("LOGOS_ADK_LEARNING_DSN")

    if backend == "postgresql" and dsn:
        return PostgreSQLLearningStore(dsn=dsn)

    if path:
        return SQLiteLearningStore(path=path)

    return SQLiteLearningStore()


def _build_quality_manager(path: str | None) -> Any:
    """Build quality manager from path or environment."""
    from logos_adk.quality_history import (
        PostgreSQLQualityHistoryStore,
        QualityExecutionManager,
        SQLiteQualityHistoryStore,
    )

    dsn = os.getenv("LOGOS_ADK_QUALITY_DSN")

    if path:
        store = SQLiteQualityHistoryStore(path=path)
    elif dsn:
        store = PostgreSQLQualityHistoryStore(dsn=dsn)
    else:
        store = SQLiteQualityHistoryStore()

    return QualityExecutionManager(store)


def _build_continuous_eval_runner(
    learning_store: "LearningStore",
    quality_manager: Any,
    engine: Any,
    *,
    path: str | None = None,
    dsn: str | None = None,
    agent: Any | None = None,
    agent_name: str | None = None,
    prompt_registry: Any | None = None,
    restore_jobs: bool = False,
    restore_all_jobs: bool = False,
) -> Any:
    """Build continuous eval runner."""
    from logos_adk.learning import ContinuousEvalRunner

    runner = ContinuousEvalRunner(
        engine=engine,
        quality_manager=quality_manager,
        path=path,
        dsn=dsn,
        agent=agent,
        agent_name=agent_name,
        prompt_registry=prompt_registry,
    )
    if restore_all_jobs:
        runner.default_agent_name = None
    if restore_jobs:
        runner.restore_jobs()
    return runner


__all__ = [
    "_build_learning_store",
    "_build_quality_manager",
    "_build_continuous_eval_runner",
]
