# #region TranslatePreviewRoutesModule [C:3] [TYPE Module] [SEMANTICS fastapi, translate, preview, review, api, search]
# @BRIEF Translation Preview session management routes.
# @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,
    PreviewRowUpdate,
)
from ._router import router

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

# #region preview_translation [C:4] [TYPE Function]
# @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 = 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


# #region update_preview_row [C:4] [TYPE Function]
# @BRIEF Approve, edit, or reject a preview row (optionally per language).
# @PRE  User has translate.job.execute permission.
# @POST  Preview row status is updated.
@router.put("/jobs/{job_id}/preview/rows/{row_key}")
async def update_preview_row(
    job_id: str,
    row_key: str,
    payload: PreviewRowUpdate,
    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),
):
    """Approve, edit, or reject a preview row (optionally per language)."""
    logger.reason(f"update_preview_row — Job: {job_id}, Row: {row_key}, Action: {payload.action}, Lang: {payload.language_code}", extra={"src": "translate_routes"})
    try:
        preview_service = TranslationPreview(db, config_manager, current_user.username)
        result = preview_service.update_preview_row(
            job_id=job_id,
            row_id=row_key,
            action=payload.action,
            translation=payload.translation,
            feedback=payload.feedback,
            language_code=payload.language_code,
        )
        return result
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion update_preview_row


# #region accept_preview_session [C:4] [TYPE Function]
# @BRIEF Accept a preview session, marking it as the quality gate for full execution.
# @PRE  User has translate.job.execute permission. Job has an ACTIVE preview session.
# @POST  Preview session is marked as APPLIED; full execution can proceed.
@router.post("/jobs/{job_id}/preview/accept")
async def accept_preview_session(
    job_id: str,
    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),
):
    """Accept a preview session, enabling full translation execution."""
    logger.reason(f"accept_preview_session — Job: {job_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        preview_service = TranslationPreview(db, config_manager, current_user.username)
        result = preview_service.accept_preview_session(job_id=job_id)
        return result
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion accept_preview_session


# #region apply_preview [C:4] [TYPE Function]
# @BRIEF Apply a preview session (alias for accept when accepting at session level).
# @PRE  User has translate.job.execute permission.
# @POST  Preview is applied.
@router.post("/preview/{session_id}/apply")
async def apply_preview(
    session_id: str,
    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),
):
    """Apply a preview session by session ID."""
    logger.reason(f"apply_preview — Session: {session_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    # Find job_id from session
    from ....models.translate import 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")
    try:
        preview_service = TranslationPreview(db, config_manager, current_user.username)
        result = preview_service.accept_preview_session(job_id=session.job_id)
        return result
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion apply_preview


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

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

@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
