# 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 convertDocument(self, parameters: Dict[str, Any]) -> ActionResult:
    documentList = parameters.get("documentList", [])
    if not documentList:
        return ActionResult.isFailure(error="documentList is required")
    
    targetFormat = parameters.get("targetFormat")
    if not targetFormat:
        return ActionResult.isFailure(error="targetFormat is required")
    
    preserveStructure = parameters.get("preserveStructure", True)
    
    # Normalize format (remove leading dot if present)
    normalizedFormat = targetFormat.strip().lstrip('.').lower()
    
    aiPrompt = f"Convert the provided document(s) to {normalizedFormat.upper()} format."
    if preserveStructure:
        aiPrompt += " Preserve all document structure including headings, tables, formatting, lists, and layout."
    aiPrompt += " Ensure the converted document maintains the same content and information as the original."
    
    # Pass parentOperationId to maintain progress hierarchy
    parentOperationId = parameters.get("parentOperationId")
    
    processParams = {
        "aiPrompt": aiPrompt,
        "documentList": documentList,
        "resultType": normalizedFormat
    }
    if parentOperationId:
        processParams["parentOperationId"] = parentOperationId
    
    return await self.process(processParams)

