# #region preview_session_serializer [C:3] [TYPE Module] [SEMANTICS preview, record, serialize, action]
# @BRIEF Serialization and action helpers for preview sessions: record serialization and per-row approve/reject/edit actions.
# @RELATION DEPENDS_ON -> [TranslationPreviewRecord]
# @RELATION DEPENDS_ON -> [TranslationPreviewLanguage]
# @RATIONALE Extracted from preview_session_ops.py for INV_7 compliance (module < 150 lines).

from typing import Any

from ...models.translate import TranslationPreviewLanguage, TranslationPreviewRecord


# #region serialize_preview_record [C:1] [TYPE Function] [SEMANTICS preview, record, serialize]
# @BRIEF Serialize a TranslationPreviewRecord to a response dict.
def serialize_preview_record(r: TranslationPreviewRecord) -> dict[str, Any]:
    """Serialize a TranslationPreviewRecord to a response dict."""
    return {
        "id": r.id,
        "source_sql": r.source_sql,
        "target_sql": r.target_sql,
        "source_object_type": r.source_object_type,
        "source_object_id": r.source_object_id,
        "source_object_name": r.source_object_name,
        "status": r.status,
        "feedback": r.feedback,
        "source_language_detected": (
            r.languages[0].source_language_detected
            if r.languages and r.languages[0].source_language_detected
            else None
        ),
        "needs_review": r.languages[0].needs_review if r.languages else False,
        "languages": [
            {
                "language_code": le.language_code,
                "source_language_detected": le.source_language_detected,
                "translated_value": le.translated_value,
                "final_value": le.final_value,
                "user_edit": le.user_edit,
                "status": le.status,
                "needs_review": le.needs_review,
            }
            for le in (r.languages or [])
        ] if r.languages else [],
    }
# #endregion serialize_preview_record


# #region apply_language_action [C:2] [TYPE Function] [SEMANTICS preview, language, action]
# @BRIEF Apply approve/reject/edit action to a TranslationPreviewLanguage entry.
def apply_language_action(
    lang_entry: TranslationPreviewLanguage,
    action: str,
    translation: str | None,
) -> None:
    """Apply action to a per-language preview entry."""
    if action == "approve":
        lang_entry.status = "approved"
    elif action == "reject":
        lang_entry.status = "rejected"
    elif action == "edit":
        lang_entry.status = "edited"
        if translation is not None:
            lang_entry.translated_value = translation
            lang_entry.final_value = translation
            lang_entry.user_edit = translation
    else:
        raise ValueError(f"Invalid action '{action}'. Use 'approve', 'reject', or 'edit'.")
# #endregion apply_language_action


# #region apply_record_action [C:2] [TYPE Function] [SEMANTICS preview, record, action]
# @BRIEF Apply approve/reject/edit action to a TranslationPreviewRecord and its language entries.
def apply_record_action(
    record: TranslationPreviewRecord,
    action: str,
    translation: str | None,
) -> None:
    """Apply action to a preview record."""
    if action == "approve":
        record.status = "APPROVED"
        for lang_entry in (record.languages or []):
            if lang_entry.status == "pending":
                lang_entry.status = "approved"
    elif action == "reject":
        record.status = "REJECTED"
        for lang_entry in (record.languages or []):
            if lang_entry.status == "pending":
                lang_entry.status = "rejected"
    elif action == "edit":
        record.status = "APPROVED"
        if translation is not None:
            record.target_sql = translation
            if record.languages:
                first_lang = record.languages[0]
                first_lang.translated_value = translation
                first_lang.final_value = translation
                first_lang.user_edit = translation
                first_lang.status = "edited"
    else:
        raise ValueError(f"Invalid action '{action}'. Use 'approve', 'reject', or 'edit'.")
# #endregion apply_record_action
# #endregion preview_session_serializer
