# #region preview_session_ops [C:3] [TYPE Module] [SEMANTICS preview, session, query]
# @defgroup Translate Module group.
# @BRIEF Preview session lifecycle operations: query preview sessions.
# @RELATION DEPENDS_ON -> [TranslationPreviewSession]
# @RELATION DEPENDS_ON -> [TranslationPreviewRecord]
# @RELATION DEPENDS_ON -> [preview_session_serializer]

from typing import Any

from sqlalchemy.orm import Session

from ...models.translate import (
    TranslationJob,
    TranslationPreviewRecord,
    TranslationPreviewSession,
)
from .preview_session_serializer import (
    serialize_preview_record as _serialize_preview_record,
)


# #region get_preview_session [C:2] [TYPE Function] [SEMANTICS preview, session, query]
# @ingroup Translate
# @BRIEF Get the latest preview session for a job with its records.
def get_preview_session(db: Session, job_id: str) -> dict[str, Any]:
    """Get the latest preview session for a job with its records."""
    session = (
        db.query(TranslationPreviewSession)
        .filter(TranslationPreviewSession.job_id == job_id)
        .order_by(TranslationPreviewSession.created_at.desc())
        .first()
    )
    if not session:
        raise ValueError(f"No preview session found for job '{job_id}'")
    records = (
        db.query(TranslationPreviewRecord)
        .filter(TranslationPreviewRecord.session_id == session.id)
        .all()
    )
    job = db.query(TranslationJob).filter(TranslationJob.id == job_id).first()
    target_languages = job.target_languages or [job.target_dialect or "en"] if job else ["en"]
    if not isinstance(target_languages, list):
        target_languages = [str(target_languages)]
    return {
        "id": session.id,
        "job_id": job_id,
        "status": session.status,
        "created_by": session.created_by,
        "created_at": session.created_at.isoformat(),
        "expires_at": session.expires_at.isoformat() if session.expires_at else None,
        "target_languages": target_languages,
        "records": [_serialize_preview_record(r) for r in records],
    }
# #endregion get_preview_session
# #endregion preview_session_ops
