# 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 findSiteByUrl(self, parameters: Dict[str, Any]) -> ActionResult:
    try:
        connectionReference = parameters.get("connectionReference")
        if not connectionReference:
            return ActionResult.isFailure(error="connectionReference parameter is required")
        
        hostname = parameters.get("hostname")
        if not hostname:
            return ActionResult.isFailure(error="hostname parameter is required")
        
        sitePath = parameters.get("sitePath")
        if not sitePath:
            return ActionResult.isFailure(error="sitePath parameter is required")
        
        # Get Microsoft connection
        connection = self.connection.getMicrosoftConnection(connectionReference)
        if not connection:
            return ActionResult.isFailure(error="No valid Microsoft connection found for the provided connection reference")
        
        # Find site by URL
        siteInfo = await self.services.sharepoint.findSiteByUrl(
            hostname=hostname,
            sitePath=sitePath
        )
        
        if not siteInfo:
            return ActionResult.isFailure(error=f"Site not found: {hostname}:/sites/{sitePath}")
        
        logger.info(f"Found SharePoint site: {siteInfo.get('displayName')} (ID: {siteInfo.get('id')})")
        
        # Generate filename
        workflowContext = self.services.chat.getWorkflowContext() if hasattr(self.services, 'chat') else None
        filename = self._generateMeaningfulFileName(
            "sharepoint_site",
            "json",
            workflowContext,
            "findSiteByUrl"
        )
        
        validationMetadata = self._createValidationMetadata(
            "findSiteByUrl",
            hostname=hostname,
            sitePath=sitePath,
            siteId=siteInfo.get("id")
        )
        
        document = ActionDocument(
            documentName=filename,
            documentData=json.dumps(siteInfo, indent=2),
            mimeType="application/json",
            validationMetadata=validationMetadata
        )
        
        return ActionResult.isSuccess(documents=[document])
        
    except Exception as e:
        errorMsg = f"Error finding SharePoint site: {str(e)}"
        logger.error(errorMsg)
        return ActionResult.isFailure(error=errorMsg)

