# #region TranslatePreviewRoutesModule [C:3] [TYPE Module] [SEMANTICS fastapi, translate, preview, api]
# @defgroup Api Module group.
# @BRIEF Translation Preview session management routes — generate preview, fetch records.
# @LAYER API


from fastapi import Depends, HTTPException, status
from sqlalchemy.orm import Session

from ....core.config_manager import ConfigManager
from ....core.database import get_db
from ....core.logger import logger
from ....dependencies import get_config_manager, get_current_user, has_permission
from ....plugins.translate.preview import TranslationPreview
from ....schemas.auth import User
from ....schemas.translate import PreviewRequest, PreviewRow
from ._router import router

# ============================================================
# Preview
# ============================================================

# #region preview_translation [C:4] [TYPE Function]
# @ingroup Api
# @BRIEF Preview a translation before applying it.
# @PRE  User has translate.job.execute permission.
# @POST  Returns a preview session with records and cost estimation.
# @SIDE_EFFECT  Fetches sample data from Superset; calls LLM provider; creates DB rows.
@router.post("/jobs/{job_id}/preview", status_code=status.HTTP_201_CREATED)
async def preview_translation(
    job_id: str,
    payload: PreviewRequest = None,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.job", "EXECUTE")),
    db: Session = Depends(get_db),
    config_manager: ConfigManager = Depends(get_config_manager),
):
    """Preview a translation before applying it."""
    logger.reason(f"preview_translation — Job: {job_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    if payload is None:
        payload = PreviewRequest()
    try:
        preview_service = TranslationPreview(db, config_manager, current_user.username)
        result = await preview_service.preview_rows(
            job_id=job_id,
            sample_size=payload.sample_size,
            prompt_template=payload.prompt_template,
            env_id=payload.env_id,
        )
        return result
    except ValueError as e:
        logger.explore("preview_translation validation failed", extra={"src": "translate_routes", "error": str(e)})
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    except Exception as e:
        logger.explore("preview_translation failed", extra={"src": "translate_routes", "error": str(e)})
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"Preview failed: {e}")
# #endregion preview_translation


# ============================================================
# Preview Records
# ============================================================

# #region get_preview_records [C:4] [TYPE Function]
# @ingroup Api
# @BRIEF Get records for a preview session.
# @PRE User has translate.job.view permission.
# @POST Returns list of preview records.

@router.get("/preview/{session_id}/records", response_model=list[PreviewRow])
async def get_preview_records(
    session_id: str,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.job", "VIEW")),
    db: Session = Depends(get_db),
):
    """Get records for a preview session."""
    logger.reason(f"get_preview_records — Session: {session_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        from ....models.translate import TranslationPreviewRecord, TranslationPreviewSession
        session = db.query(TranslationPreviewSession).filter(TranslationPreviewSession.id == session_id).first()
        if not session:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Preview session '{session_id}' not found")
        records = (
            db.query(TranslationPreviewRecord)
            .filter(TranslationPreviewRecord.session_id == session_id)
            .all()
        )
        return [
            PreviewRow(
                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,
            )
            for r in records
        ]
    except HTTPException:
        raise
    except Exception as e:
        logger.explore("get_preview_records failed", extra={"src": "translate_routes", "error": str(e)})
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion get_preview_records

# #endregion TranslatePreviewRoutesModule
