# #region orchestrator_query [C:3] [TYPE Module] [SEMANTICS translate, query, records, history]
# @BRIEF Query translation run records and history with pagination.
# @RELATION DEPENDS_ON -> [TranslationRecord]
# @RELATION DEPENDS_ON -> [TranslationRun]

from typing import Any

from sqlalchemy.orm import Session, selectinload

from ...models.translate import TranslationRecord, TranslationRun


# #region get_run_records [C:2] [TYPE Function] [SEMANTICS records, query, paginated]
# @BRIEF Get paginated records for a run.
def get_run_records(
    db: Session,
    run_id: str,
    page: int = 1,
    page_size: int = 50,
    status_filter: str | None = None,
) -> dict[str, Any]:
    """Get paginated records for a run."""
    query = (
        db.query(TranslationRecord)
        .options(selectinload(TranslationRecord.languages))
        .filter(TranslationRecord.run_id == run_id)
    )
    if status_filter:
        query = query.filter(TranslationRecord.status == status_filter)

    total = query.count()
    offset_val = (page - 1) * page_size
    records = (
        query.order_by(TranslationRecord.created_at.desc())
        .offset(offset_val)
        .limit(page_size)
        .all()
    )

    return {
        "items": [
            {
                "id": r.id,
                "batch_id": r.batch_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,
                "error_message": r.error_message,
                "created_at": r.created_at.isoformat() if r.created_at else None,
                "languages": [
                    {
                        "language_code": tl.language_code,
                        "translated_value": tl.translated_value,
                        "final_value": tl.final_value or tl.translated_value,
                        "source_language_detected": tl.source_language_detected,
                        "status": tl.status,
                        "needs_review": tl.needs_review or False,
                    }
                    for tl in (r.languages or [])
                ],
            }
            for r in records
        ],
        "total": total,
        "page": page,
        "page_size": page_size,
        "status_filter": status_filter,
    }
# #endregion get_run_records


# #region get_run_history [C:2] [TYPE Function] [SEMANTICS history, query, paginated]
# @BRIEF Get run history for a job with pagination.
def get_run_history(
    db: Session,
    job_id: str,
    page: int = 1,
    page_size: int = 20,
) -> tuple[int, list[dict[str, Any]]]:
    """Get run history for a job with pagination."""
    query = db.query(TranslationRun).filter(TranslationRun.job_id == job_id)
    total = query.count()
    runs = (
        query.order_by(TranslationRun.created_at.desc())
        .offset((page - 1) * page_size)
        .limit(page_size)
        .all()
    )

    return total, [
        {
            "id": r.id,
            "job_id": r.job_id,
            "status": r.status,
            "started_at": r.started_at.isoformat() if r.started_at else None,
            "completed_at": r.completed_at.isoformat() if r.completed_at else None,
            "error_message": r.error_message,
            "total_records": r.total_records or 0,
            "successful_records": r.successful_records or 0,
            "failed_records": r.failed_records or 0,
            "skipped_records": r.skipped_records or 0,
            "insert_status": r.insert_status,
            "superset_execution_id": r.superset_execution_id,
            "created_by": r.created_by,
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in runs
    ]
# #endregion get_run_history
# #endregion orchestrator_query
