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

"""
Connection helper for SharePoint operations.
Handles Microsoft connection management and SharePoint service configuration.
"""

import logging
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)

class ConnectionHelper:
    """Helper for Microsoft connection management in SharePoint operations"""
    
    def __init__(self, methodInstance):
        """
        Initialize connection helper.
        
        Args:
            methodInstance: Instance of MethodSharepoint (for access to services)
        """
        self.method = methodInstance
        self.services = methodInstance.services
    
    def getMicrosoftConnection(self, connectionReference: str) -> Optional[Dict[str, Any]]:
        """
        Get Microsoft connection from connection reference and configure SharePoint service.
        
        Args:
            connectionReference: Connection reference string
            
        Returns:
            Dict with connection info or None if failed
        """
        try:
            userConnection = self.services.chat.getUserConnectionFromConnectionReference(connectionReference)
            if not userConnection:
                logger.warning(f"No user connection found for reference: {connectionReference}")
                return None
                
            if userConnection.authority.value != "msft":
                logger.warning(f"Connection {userConnection.id} is not Microsoft (authority: {userConnection.authority.value})")
                return None
            
            # Check if connection is active or pending (pending means OAuth in progress)
            if userConnection.status.value not in ["active", "pending"]:
                logger.warning(f"Connection {userConnection.id} status is not active/pending: {userConnection.status.value}")
                return None
            
            # Configure SharePoint service with the UserConnection
            if not self.services.sharepoint.setAccessTokenFromConnection(userConnection):
                logger.warning(f"Failed to configure SharePoint service with connection {userConnection.id}")
                return None
            
            logger.info(f"Successfully configured SharePoint service with Microsoft connection: {userConnection.id}, status: {userConnection.status.value}, externalId: {userConnection.externalId}")
            
            return {
                "id": userConnection.id,
                "userConnection": userConnection,
                "scopes": ["Sites.ReadWrite.All", "Files.ReadWrite.All", "User.Read"]  # SharePoint scopes
            }
        except Exception as e:
            logger.error(f"Error getting Microsoft connection: {str(e)}")
            return None

