# #region TranslateCorrectionRoutesModule [C:2] [TYPE Module] [SEMANTICS fastapi, translate, api, search]
# @BRIEF Term correction submission endpoints.
# @LAYER API

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

from ....core.database import get_db
from ....core.logger import logger
from ....dependencies import get_current_user, has_permission
from ....plugins.translate.dictionary import DictionaryManager
from ....schemas.auth import User
from ....schemas.translate import (
    TermCorrectionBulkSubmit,
    TermCorrectionSubmit,
)
from ._router import router

# ============================================================
# Corrections
# ============================================================

# #region submit_correction [C:4] [TYPE Function]
# @BRIEF Submit a term correction from a run result review.
# @PRE User has translate.dictionary.edit permission.
# @POST Correction applied with conflict detection.
# @SIDE_EFFECT Creates/updates DictionaryEntry row; commits.
# @RELATION DEPENDS_ON -> [DictionaryManager]
@router.post("/corrections")
async def submit_correction(
    payload: TermCorrectionSubmit,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.dictionary", "EDIT")),
    db: Session = Depends(get_db),
):
    """Submit a term correction from a run result review."""
    logger.reason(f"submit_correction — User: {current_user.username}", extra={"src": "translate_routes"})
    if not payload.dictionary_id:
        raise HTTPException(status_code=422, detail="dictionary_id is required")
    try:
        result = DictionaryManager.submit_correction(
            db,
            dict_id=payload.dictionary_id,
            source_term=payload.source_term,
            incorrect_target_term=payload.incorrect_target_term,
            corrected_target_term=payload.corrected_target_term,
            origin_run_id=payload.origin_run_id,
            origin_row_key=payload.origin_row_key,
            origin_user_id=current_user.username,
            context_data=payload.context_data,
            usage_notes=payload.usage_notes,
            keep_context=payload.keep_context,
        )
        return result
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion submit_correction


# #region submit_bulk_corrections [C:4] [TYPE Function]
# @BRIEF Submit multiple term corrections atomically.
# @PRE User has translate.dictionary.edit permission.
# @POST All corrections applied or none with conflict list.
# @SIDE_EFFECT Creates/updates DictionaryEntry rows; commits once.
# @RELATION DEPENDS_ON -> [DictionaryManager]
# @COMPLEXITY 4

@router.post("/corrections/bulk")
async def submit_bulk_corrections(
    payload: TermCorrectionBulkSubmit,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.dictionary", "EDIT")),
    db: Session = Depends(get_db),
):
    """Submit multiple term corrections atomically."""
    logger.reason(f"submit_bulk_corrections — User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        corr_list = []
        for c in payload.corrections:
            corr_list.append({
                "source_term": c.source_term,
                "incorrect_target_term": c.incorrect_target_term,
                "corrected_target_term": c.corrected_target_term,
                "origin_run_id": c.origin_run_id,
                "origin_row_key": c.origin_row_key,
            })
        result = DictionaryManager.submit_bulk_corrections(
            db,
            dict_id=payload.dictionary_id,
            corrections=corr_list,
            origin_user_id=current_user.username,
        )
        if result.get("status") == "conflicts":
            raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=result)
        return result
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion submit_bulk_corrections

# #endregion TranslateCorrectionRoutesModule
