# 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 importTicketsFromJson(self, parameters: Dict[str, Any]) -> ActionResult:
    try:
        connectionIdParam = parameters.get("connectionId")
        if not connectionIdParam:
            return ActionResult.isFailure(error="connectionId parameter is required")
        
        ticketDataParam = parameters.get("ticketData")
        if not ticketDataParam:
            return ActionResult.isFailure(error="ticketData parameter is required")
        
        # Get connection ID from document if it's a reference
        connectionId = None
        if isinstance(connectionIdParam, str):
            connectionInfo = self.documentParsing.parseJsonFromDocument(connectionIdParam)
            if connectionInfo and "connectionId" in connectionInfo:
                connectionId = connectionInfo["connectionId"]
            else:
                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"]
        
        # Get ticket data from document
        ticketDataJson = self.documentParsing.parseJsonFromDocument(ticketDataParam)
        if ticketDataJson is None:
            return ActionResult.isFailure(error="Could not parse ticket data from document reference")
        
        # Ensure it's a list
        if not isinstance(ticketDataJson, list):
            return ActionResult.isFailure(error="ticketData must be a JSON array")
        
        # Import tickets
        await syncInterface.importListToTickets(ticketDataJson)
        
        logger.info(f"Imported {len(ticketDataJson)} tickets to JIRA")
        
        # Generate filename
        workflowContext = self.services.chat.getWorkflowContext() if hasattr(self.services, 'chat') else None
        filename = self._generateMeaningfulFileName(
            "jira_import_result",
            "json",
            workflowContext,
            "importTicketsFromJson"
        )
        
        importResult = {
            "imported": len(ticketDataJson),
            "connectionId": connectionId,
        }
        
        validationMetadata = self._createValidationMetadata(
            "importTicketsFromJson",
            connectionId=connectionId,
            importedCount=len(ticketDataJson)
        )
        
        document = ActionDocument(
            documentName=filename,
            documentData=json.dumps(importResult, indent=2),
            mimeType="application/json",
            validationMetadata=validationMetadata
        )
        
        return ActionResult.isSuccess(documents=[document])
        
    except Exception as e:
        errorMsg = f"Error importing tickets to JIRA: {str(e)}"
        logger.error(errorMsg)
        return ActionResult.isFailure(error=errorMsg)

