"""Database row converters for retrieval learning models."""
from __future__ import annotations

import json
import sqlite3
from typing import Any

from .models import (
    ReindexRequest,
    ReindexTrigger,
    RetrievalEvent,
    RetrievalProfile,
    SourceDocumentSnapshot,
    SourceUsefulnessScore,
)


def row_to_event(row: sqlite3.Row) -> RetrievalEvent:
    """Convert database row to RetrievalEvent."""
    return RetrievalEvent(
        id=row["id"],
        trace_id=row["trace_id"],
        session_id=row["session_id"],
        workspace_id=None if row["workspace_id"] == "__global__" else row["workspace_id"],
        task_type=None if row["task_type"] == "__all__" else row["task_type"],
        user_segment=None if row["user_segment"] == "__all__" else row["user_segment"],
        prompt_name=row["prompt_name"],
        prompt_version=row["prompt_version"],
        original_query=row["original_query"],
        effective_query=row["effective_query"],
        limit=row["limit_value"],
        filter=json.loads(row["filter_json"]) if row["filter_json"] else None,
        chunks=json.loads(row["chunks_json"]),
        quality_score=float(row["quality_score"]),
        bad_context_detected=bool(row["bad_context_detected"]),
        synced_at=row["synced_at"],
        applied_feedback_ids=json.loads(row["applied_feedback_ids_json"]),
        applied_outcome_ids=json.loads(row["applied_outcome_ids_json"]),
        created_at=row["created_at"],
    )


def row_to_source_score(row: sqlite3.Row, workspace_id: str | None) -> SourceUsefulnessScore:
    """Convert database row to SourceUsefulnessScore."""
    return SourceUsefulnessScore(
        workspace_id=workspace_id,
        source_key=row["source_key"],
        connector=row["connector"],
        helpful_count=int(row["helpful_count"]),
        harmful_count=int(row["harmful_count"]),
        accepted_count=int(row["accepted_count"]),
        rejected_count=int(row["rejected_count"]),
        usefulness_score=float(row["usefulness_score"]),
        last_updated=row["last_updated"],
    )


def row_to_reindex_trigger(row: sqlite3.Row, workspace_id: str | None) -> ReindexTrigger:
    """Convert database row to ReindexTrigger."""
    return ReindexTrigger(
        id=row["id"],
        workspace_id=workspace_id,
        source_key=row["source_key"],
        reason=row["reason"],
        severity=row["severity"],
        occurrences=int(row["occurrences"]),
        status=row["status"],
        suggested_chunk_size=row["suggested_chunk_size"],
        suggested_overlap=row["suggested_overlap"],
        metadata=json.loads(row["metadata_json"]) if row["metadata_json"] else {},
        created_at=row["created_at"],
        updated_at=row["updated_at"],
    )


def row_to_reindex_request(row: sqlite3.Row, workspace_id: str | None) -> ReindexRequest:
    """Convert database row to ReindexRequest."""
    return ReindexRequest(
        id=row["id"],
        workspace_id=workspace_id,
        source_key=row["source_key"],
        reason=row["reason"],
        requested_by=row["requested_by"],
        status=row["status"],
        metadata=json.loads(row["metadata_json"]) if row["metadata_json"] else {},
        created_at=row["created_at"],
        updated_at=row["updated_at"],
    )


def row_to_source_document(row: sqlite3.Row, workspace_id: str | None) -> SourceDocumentSnapshot:
    """Convert database row to SourceDocumentSnapshot."""
    return SourceDocumentSnapshot(
        workspace_id=workspace_id,
        source_key=row["source_key"],
        document_id=row["document_id"],
        content=row["content"],
        metadata=json.loads(row["metadata_json"]) if row["metadata_json"] else {},
        source_ref=row["source_ref"],
        updated_at=row["updated_at"],
    )


def row_to_profile(row: sqlite3.Row) -> RetrievalProfile:
    """Convert database row to RetrievalProfile."""
    return RetrievalProfile(
        workspace_id=None if row["workspace_id"] == "__global__" else row["workspace_id"],
        task_type=None if row["task_type"] == "__all__" else row["task_type"],
        user_segment=None if row["user_segment"] == "__all__" else row["user_segment"],
        limit=row["limit_value"],
        filter=json.loads(row["filter_json"]) if row["filter_json"] else {},
        success_count=int(row["success_count"]),
        failure_count=int(row["failure_count"]),
        score=0.0,  # Calculated field
        last_updated=row["last_updated"],
    )


def source_score_to_dict(score: SourceUsefulnessScore) -> dict[str, Any]:
    """Convert SourceUsefulnessScore to dictionary for export."""
    return {
        "workspace_id": score.workspace_id,
        "source_key": score.source_key,
        "connector": score.connector,
        "usefulness_score": score.usefulness_score,
        "helpful_count": score.helpful_count,
        "harmful_count": score.harmful_count,
        "accepted_count": score.accepted_count,
        "rejected_count": score.rejected_count,
        "last_updated": score.last_updated,
    }
