"""Feedback and outcome route handlers - /feedback, /outcomes endpoints."""
from __future__ import annotations

import uuid
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any


from ..schemas import FeedbackRequest, FeedbackResponse, OutcomeRequest, OutcomeResponse

if TYPE_CHECKING:
    pass


def get_feedback_api(learning_store: Any | None = None) -> Any:
    """Get or create FeedbackAPI instance."""
    if learning_store is None:
        return None
    
    if hasattr(learning_store, "feedback"):
        return learning_store.feedback
    
    return learning_store


async def capture_feedback_handler(
    request: FeedbackRequest,
    learning_store: Any | None = None,
) -> FeedbackResponse:
    """Handle POST /feedback - capture user feedback."""
    feedback_api = get_feedback_api(learning_store)
    
    feedback_id = uuid.uuid4().hex[:12]
    now = datetime.now(UTC).isoformat()
    
    if feedback_api and callable(getattr(feedback_api, "record_feedback", None)):
        try:
            feedback_api.record_feedback(
                kind=request.kind,
                run_id=request.run_id,
                trace_id=request.trace_id,
                rating=request.rating,
                suggestion_outcome=request.suggestion_outcome,
                corrected_output=request.corrected_output,
                correction_notes=request.correction_notes,
                expected_output=request.expected_output,
                failure_types=request.failure_types or [],
                metadata=request.metadata or {},
            )
        except Exception:
            pass
    
    return FeedbackResponse(
        id=feedback_id,
        run_id=request.run_id,
        trace_id=request.trace_id or "unknown",
        kind=request.kind,
        session_id=None,
        workspace_id=None,
        prompt_version=None,
        model=None,
        config_fingerprint=None,
        rating=request.rating,
        suggestion_outcome=request.suggestion_outcome,
        corrected_output=request.corrected_output,
        correction_notes=request.correction_notes,
        expected_output=request.expected_output,
        failure_types=request.failure_types or [],
        metadata=request.metadata or {},
        created_at=now,
    )


async def capture_outcome_handler(
    request: OutcomeRequest,
    learning_store: Any | None = None,
) -> OutcomeResponse:
    """Handle POST /outcomes - capture business outcome."""
    feedback_api = get_feedback_api(learning_store)
    
    outcome_id = uuid.uuid4().hex[:12]
    now = datetime.now(UTC).isoformat()
    
    if feedback_api and callable(getattr(feedback_api, "record_outcome", None)):
        try:
            feedback_api.record_outcome(
                kind=request.kind,
                run_id=request.run_id,
                trace_id=request.trace_id,
                value=request.value,
                metadata=request.metadata or {},
            )
        except Exception:
            pass
    
    return OutcomeResponse(
        id=outcome_id,
        run_id=request.run_id,
        trace_id=request.trace_id or "unknown",
        kind=request.kind,
        session_id=None,
        workspace_id=None,
        prompt_version=None,
        model=None,
        config_fingerprint=None,
        value=request.value,
        metadata=request.metadata or {},
        created_at=now,
    )


__all__ = ["capture_feedback_handler", "capture_outcome_handler"]
