import uuid
from typing import Any, Dict, List, Optional
from decentriq_dcr_compiler.schemas import Permission


class Participant:
    """
    A participant in a Data Clean Room.
    """

    def __init__(
        self,
        emails: List[str],
        permissions: List[Permission],
        role: str,
        id: Optional[str] = None,
        organization_id: Optional[str] = None,
        member_permissions: Optional[Dict[str, List[Permission]]] = None,
    ):
        """
        Initialize a participant.

        **Parameters**:
        - `emails`: The emails of the participant
        - `permissions`: The permissions of the participant
        - `role`: The role of the participant
        - `id`: The id of the participant
        - `organization_id`: The organization id of the participant
        - `member_permissions`: Specific permissions for the participant
        """
        self.id = str(uuid.uuid4()) if id is None else id
        self.role = role
        self.emails = emails
        self.permissions = permissions
        self.organization_id = organization_id
        self.member_permissions = member_permissions

    def as_dict(self) -> Dict[str, Any]:
        """
        Return the participant as a dictionary.

        **Returns**:
        - The participant as a dictionary
        """
        if self.member_permissions is None:
            member_permissions = None
        else:
            member_permissions = {
                email: [permission.value for permission in permissions]
                for email, permissions in self.member_permissions.items()
            }
        return {
            "id": self.id,
            "role": self.role,
            "emails": self.emails,
            "permissions": [permission.value for permission in self.permissions],
            "organizationId": self.organization_id,
            "memberPermissions": member_permissions,
        }

    def can_export_audience(self) -> bool:
        """
        Check if the participant has the export audience permission.

        **Returns**:
        - True if the participant has the export audience permission, False otherwise
        """
        return Permission.EXPORT_AUDIENCE.value in self.permissions
