# Copyright (c) 2025 Patrick Motsch
# All rights reserved.

import logging
from typing import Dict, Any
from modules.datamodels.datamodelChat import ActionResult

logger = logging.getLogger(__name__)

async def translateDocument(self, parameters: Dict[str, Any]) -> ActionResult:
    documentList = parameters.get("documentList", [])
    if not documentList:
        return ActionResult.isFailure(error="documentList is required")
    
    targetLanguage = parameters.get("targetLanguage")
    if not targetLanguage:
        return ActionResult.isFailure(error="targetLanguage is required")
    
    sourceLanguage = parameters.get("sourceLanguage")
    preserveFormatting = parameters.get("preserveFormatting", True)
    resultType = parameters.get("resultType")
    
    aiPrompt = f"Translate the provided document(s) to {targetLanguage}."
    if sourceLanguage:
        aiPrompt += f" The source language is {sourceLanguage}."
    if preserveFormatting:
        aiPrompt += " Preserve all formatting, structure, tables, and layout exactly as they appear in the original document."
    else:
        aiPrompt += " Focus on accurate translation of content."
    aiPrompt += " Maintain the same document structure, headings, and organization."
    
    # Pass parentOperationId to maintain progress hierarchy
    parentOperationId = parameters.get("parentOperationId")
    
    processParams = {
        "aiPrompt": aiPrompt,
        "documentList": documentList,
        "generationIntent": "document"  # NEW: Explicit intent
    }
    if resultType:
        processParams["resultType"] = resultType
    if parentOperationId:
        processParams["parentOperationId"] = parentOperationId
    
    return await self.process(processParams)

