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

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

logger = logging.getLogger(__name__)

async def exportTicketsAsJson(self, parameters: Dict[str, Any]) -> ActionResult:
    try:
        connectionIdParam = parameters.get("connectionId")
        if not connectionIdParam:
            return ActionResult.isFailure(error="connectionId parameter is required")
        
        # Get connection ID from document if it's a reference
        connectionId = None
        if isinstance(connectionIdParam, str):
            # Try to parse from document reference
            connectionInfo = self.documentParsing.parseJsonFromDocument(connectionIdParam)
            if connectionInfo and "connectionId" in connectionInfo:
                connectionId = connectionInfo["connectionId"]
            else:
                # Assume it's the connection ID directly
                connectionId = connectionIdParam
        
        if not connectionId or connectionId not in self._connections:
            return ActionResult.isFailure(error=f"Connection ID {connectionIdParam} not found. Ensure connectJira was called first.")
        
        connection = self._connections[connectionId]
        syncInterface = connection["interface"]
        
        # Export tickets
        dataList = await syncInterface.exportTicketsAsList()
        
        logger.info(f"Exported {len(dataList)} tickets from JIRA")
        
        # Generate filename
        workflowContext = self.services.chat.getWorkflowContext() if hasattr(self.services, 'chat') else None
        filename = self._generateMeaningfulFileName(
            "jira_tickets_export",
            "json",
            workflowContext,
            "exportTicketsAsJson"
        )
        
        validationMetadata = self._createValidationMetadata(
            "exportTicketsAsJson",
            connectionId=connectionId,
            ticketCount=len(dataList)
        )
        
        document = ActionDocument(
            documentName=filename,
            documentData=json.dumps(dataList, indent=2, ensure_ascii=False),
            mimeType="application/json",
            validationMetadata=validationMetadata
        )
        
        return ActionResult.isSuccess(documents=[document])
        
    except Exception as e:
        errorMsg = f"Error exporting tickets from JIRA: {str(e)}"
        logger.error(errorMsg)
        return ActionResult.isFailure(error=errorMsg)

