"""Dataset building route handlers."""
from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ...schemas import DatasetBuildRequest, DatasetBuildResponse

if TYPE_CHECKING:
    pass


async def build_dataset_handler(
    request: DatasetBuildRequest,
    learning_store: Any | None = None,
) -> DatasetBuildResponse:
    """Handle POST /learning/datasets/build - build dataset from feedback."""
    workspace_id = request.workspace_id
    agent_name = request.agent_name
    limit = request.limit
    include_unreviewed = request.include_unreviewed
    
    if learning_store is None:
        return DatasetBuildResponse(
            summary={"error": "learning_store not configured"},
            items=[],
        )
    
    try:
        if hasattr(learning_store, "build_dataset"):
            dataset = learning_store.build_dataset(
                workspace_id=workspace_id,
                agent_name=agent_name,
                limit=limit,
                include_unreviewed=include_unreviewed,
            )
        elif hasattr(learning_store, "feedback"):
            feedback_api = learning_store.feedback
            feedback_list = feedback_api.list_feedback(
                workspace_id=workspace_id,
                limit=limit,
            )
            dataset = {
                "feedback_count": len(feedback_list),
                "items": [
                    {
                        "id": f.id,
                        "kind": f.kind,
                        "rating": f.rating,
                        "created_at": f.created_at,
                    }
                    for f in feedback_list[:limit]
                ],
            }
        else:
            dataset = {"error": "dataset building not supported"}
        
        return DatasetBuildResponse(
            summary={"total_items": len(dataset.get("items", []))},
            items=dataset.get("items", []),
        )
    except Exception as e:
        return DatasetBuildResponse(
            summary={"error": str(e)},
            items=[],
        )


__all__ = ["build_dataset_handler"]
