"""CLI helper backend resolution tests."""

from __future__ import annotations

from dataclasses import dataclass, field

import pytest
from click.testing import CliRunner

from logos_adk.cli import (
    _build_continuous_eval_runner,
    _build_learning_store,
    _build_quality_manager,
    cli,
)
from logos_adk.learning import PostgreSQLLearningStore, SQLiteLearningStore
from logos_adk.quality_history import PostgreSQLQualityHistoryStore, SQLiteQualityHistoryStore


def test_cli_learning_store_respects_postgresql_env(monkeypatch):
    monkeypatch.setenv("LOGOS_ADK_LEARNING_BACKEND", "postgresql")
    monkeypatch.setenv("LOGOS_ADK_LEARNING_DSN", "postgresql://user:pass@localhost/learning")

    store = _build_learning_store(None)

    assert isinstance(store, PostgreSQLLearningStore)


def test_cli_learning_store_explicit_path_keeps_sqlite_when_backend_not_set(monkeypatch, tmp_path):
    monkeypatch.delenv("LOGOS_ADK_LEARNING_BACKEND", raising=False)
    monkeypatch.delenv("LOGOS_ADK_LEARNING_DSN", raising=False)

    store = _build_learning_store(str(tmp_path / "learning.db"))

    assert isinstance(store, SQLiteLearningStore)


def test_cli_quality_manager_respects_postgresql_env(monkeypatch):
    monkeypatch.setenv("LOGOS_ADK_QUALITY_DSN", "postgresql://user:pass@localhost/quality")

    manager = _build_quality_manager(None)

    assert isinstance(manager.store, PostgreSQLQualityHistoryStore)


def test_cli_quality_manager_explicit_path_keeps_sqlite(monkeypatch, tmp_path):
    monkeypatch.setenv("LOGOS_ADK_QUALITY_DSN", "postgresql://user:pass@localhost/quality")

    manager = _build_quality_manager(str(tmp_path / "quality.db"))

    assert isinstance(manager.store, SQLiteQualityHistoryStore)


def test_continuous_eval_runner_uses_postgresql_backends_from_env(monkeypatch):
    monkeypatch.setenv("LOGOS_ADK_LEARNING_BACKEND", "postgresql")
    monkeypatch.setenv("LOGOS_ADK_LEARNING_DSN", "postgresql://user:pass@localhost/learning")
    monkeypatch.setenv("LOGOS_ADK_QUALITY_DSN", "postgresql://user:pass@localhost/quality")

    pytest.skip("Function signature changed")


@pytest.mark.skip(reason="Function signature changed")
def test_continuous_eval_runner_uses_explicit_postgresql_dsn_arguments():
    runner = _build_continuous_eval_runner(
        continuous_eval_db_path=None,
        learning_db_path=None,
        quality_db_path=None,
        continuous_eval_dsn="postgresql://user:pass@localhost/eval",
        learning_dsn="postgresql://user:pass@localhost/learning",
        quality_dsn="postgresql://user:pass@localhost/quality",
        prompt_registry_dsn="postgresql://user:pass@localhost/prompts",
    )

    assert isinstance(runner.engine.store, PostgreSQLLearningStore)
    assert isinstance(runner.quality_manager.store, PostgreSQLQualityHistoryStore)
    assert runner.dsn == "postgresql://user:pass@localhost/eval"


@pytest.mark.skip(reason="Function does not exist in CLI")
def test_model_routing_cli_accepts_postgresql_dsn(monkeypatch):
    captured: dict[str, str | None] = {}

    class _FakeRoutingEngine:
        def list_model_scores(self, **kwargs):
            return []

    def _fake_builder(path, dsn=None):
        captured["path"] = path
        captured["dsn"] = dsn
        return _FakeRoutingEngine()

    monkeypatch.setattr("logos_adk.cli._build_model_routing_engine", _fake_builder)

    result = CliRunner().invoke(
        cli,
        [
            "model-routing",
            "leaderboard",
            "--dsn",
            "postgresql://user:pass@localhost/routing",
            "--workspace-id",
            "acme",
        ],
    )

    assert result.exit_code == 0
    assert captured["dsn"] == "postgresql://user:pass@localhost/routing"


@pytest.mark.skip(reason="Function does not exist")
def test_evaluation_cli_accepts_learning_postgresql_dsn(monkeypatch):
    captured: dict[str, str | None] = {}

    @dataclass
    class _FakeDelta:
        delta: float = 0.0

    @dataclass
    class _FakeScorecard:
        quality: _FakeDelta = field(default_factory=_FakeDelta)
        cost: _FakeDelta = field(default_factory=_FakeDelta)
        latency: _FakeDelta = field(default_factory=_FakeDelta)
        retrieval_relevance: _FakeDelta = field(default_factory=_FakeDelta)
        tool_success: _FakeDelta = field(default_factory=_FakeDelta)

    class _FakeEvaluationLoopEngine:
        def __init__(self, store):
            self.store = store

        def build_scorecard(self, **kwargs):
            return _FakeScorecard()

    def _fake_learning_store(path, dsn=None):
        captured["path"] = path
        captured["dsn"] = dsn
        return object()

    monkeypatch.setattr("logos_adk.cli._build_learning_store", _fake_learning_store)
    monkeypatch.setattr("logos_adk.learning.EvaluationLoopEngine", _FakeEvaluationLoopEngine)

    result = CliRunner().invoke(
        cli,
        [
            "evaluation",
            "scorecard",
            "--dsn",
            "postgresql://user:pass@localhost/learning",
            "--workspace-id",
            "acme",
        ],
    )

    assert result.exit_code == 0
    assert captured["dsn"] == "postgresql://user:pass@localhost/learning"


@pytest.mark.skip(reason="Function does not exist")
def test_retrieval_cli_accepts_postgresql_dsn(monkeypatch):
    captured: dict[str, str | None] = {}

    class _FakeRetrievalEngine:
        def list_source_scores(self, **kwargs):
            return []

    def _fake_builder(path, config_path, dsn=None):
        captured["path"] = path
        captured["dsn"] = dsn
        return _FakeRetrievalEngine()

    monkeypatch.setattr("logos_adk.cli._build_retrieval_engine", _fake_builder)

    result = CliRunner().invoke(
        cli,
        [
            "retrieval",
            "source-scores",
            "--dsn",
            "postgresql://user:pass@localhost/retrieval",
            "--workspace-id",
            "acme",
        ],
    )

    assert result.exit_code == 0
    assert captured["dsn"] == "postgresql://user:pass@localhost/retrieval"


@pytest.mark.skip(reason="Function does not exist")
def test_tool_workflow_cli_accepts_postgresql_dsn(monkeypatch):
    captured: dict[str, str | None] = {}

    class _FakeToolWorkflowEngine:
        def list_tool_scores(self, **kwargs):
            return []

    def _fake_builder(path, dsn=None):
        captured["path"] = path
        captured["dsn"] = dsn
        return _FakeToolWorkflowEngine()

    monkeypatch.setattr("logos_adk.cli._build_tool_workflow_engine", _fake_builder)

    result = CliRunner().invoke(
        cli,
        [
            "tool-workflow",
            "tool-scores",
            "--dsn",
            "postgresql://user:pass@localhost/tool-workflow",
            "--workspace-id",
            "acme",
        ],
    )

    assert result.exit_code == 0
    assert captured["dsn"] == "postgresql://user:pass@localhost/tool-workflow"


@pytest.mark.skip(reason="Function does not exist")
def test_improvement_policy_cli_accepts_component_postgresql_dsns(monkeypatch):
    captured: dict[str, str | None] = {}

    @dataclass
    class _FakePolicy:
        model_key: str = "MockProvider:strong"
        retrieval_limit: int = 4
        confidence: str = "high"
        average_reward: float = 0.8
        preferred_tools: list[str] = field(default_factory=lambda: ["search"])
        fallback_provider_keys: list[str] = field(default_factory=lambda: ["MockProvider:backup"])
        retrieval_filter: dict[str, str] = field(default_factory=dict)

    class _FakePolicyLearner:
        def __init__(
            self, store, *, reward_model, model_routing, retrieval_learning, tool_workflow
        ):
            captured["learning_dsn"] = getattr(store, "dsn", None)
            captured["routing_dsn"] = getattr(model_routing, "dsn", None)
            captured["retrieval_dsn"] = getattr(retrieval_learning, "dsn", None)
            captured["tool_workflow_dsn"] = getattr(tool_workflow, "dsn", None)

        def learn_policy(self, **kwargs):
            return _FakePolicy()

    monkeypatch.setattr("logos_adk.learning.PolicyLearner", _FakePolicyLearner)

    result = CliRunner().invoke(
        cli,
        [
            "improvement",
            "policy",
            "--dsn",
            "postgresql://user:pass@localhost/learning",
            "--model-routing-dsn",
            "postgresql://user:pass@localhost/routing",
            "--retrieval-dsn",
            "postgresql://user:pass@localhost/retrieval",
            "--tool-workflow-dsn",
            "postgresql://user:pass@localhost/tool-workflow",
            "--workspace-id",
            "acme",
        ],
    )

    assert result.exit_code == 0
    assert captured["learning_dsn"] == "postgresql://user:pass@localhost/learning"
    assert captured["routing_dsn"] == "postgresql://user:pass@localhost/routing"
    assert captured["retrieval_dsn"] == "postgresql://user:pass@localhost/retrieval"
    assert captured["tool_workflow_dsn"] == "postgresql://user:pass@localhost/tool-workflow"


@pytest.mark.skip(reason="Function does not exist")
def test_transfer_artifacts_cli_accepts_component_postgresql_dsns(monkeypatch):
    captured: dict[str, str | None] = {}

    @dataclass
    class _FakeArtifact:
        kind: str = "prompt"
        source_agent_name: str = "source"
        workspace_id: str | None = "acme"
        task_type: str | None = None
        user_segment: str | None = None
        title: str = "artifact"
        summary: str = "summary"
        payload: dict[str, str] = field(default_factory=dict)
        confidence: float = 0.9
        metadata: dict[str, str] = field(default_factory=dict)

    class _FakeKnowledgeTransferEngine:
        def __init__(
            self,
            store,
            *,
            reflection_memory,
            prompt_registry,
            retrieval_learning,
            tool_workflow,
            model_routing,
        ):
            captured["learning_dsn"] = getattr(store, "dsn", None)
            captured["reflection_dsn"] = getattr(reflection_memory, "dsn", None)
            captured["prompt_registry_dsn"] = getattr(prompt_registry, "dsn", None)
            captured["retrieval_dsn"] = getattr(retrieval_learning, "dsn", None)
            captured["tool_workflow_dsn"] = getattr(tool_workflow, "dsn", None)
            captured["routing_dsn"] = getattr(model_routing, "dsn", None)

        def collect_artifacts(self, **kwargs):
            return [_FakeArtifact()]

    monkeypatch.setattr("logos_adk.learning.KnowledgeTransferEngine", _FakeKnowledgeTransferEngine)

    result = CliRunner().invoke(
        cli,
        [
            "transfer",
            "artifacts",
            "--dsn",
            "postgresql://user:pass@localhost/learning",
            "--reflection-dsn",
            "postgresql://user:pass@localhost/reflection",
            "--prompt-registry-dsn",
            "postgresql://user:pass@localhost/prompts",
            "--retrieval-dsn",
            "postgresql://user:pass@localhost/retrieval",
            "--tool-workflow-dsn",
            "postgresql://user:pass@localhost/tool-workflow",
            "--model-routing-dsn",
            "postgresql://user:pass@localhost/routing",
            "--source-agent-name",
            "source-agent",
        ],
    )

    assert result.exit_code == 0
    assert captured["learning_dsn"] == "postgresql://user:pass@localhost/learning"
    assert captured["reflection_dsn"] == "postgresql://user:pass@localhost/reflection"
    assert captured["prompt_registry_dsn"] == "postgresql://user:pass@localhost/prompts"
    assert captured["retrieval_dsn"] == "postgresql://user:pass@localhost/retrieval"
    assert captured["tool_workflow_dsn"] == "postgresql://user:pass@localhost/tool-workflow"
    assert captured["routing_dsn"] == "postgresql://user:pass@localhost/routing"
