# LocalStack Resource Provider Scaffolding v2
from __future__ import annotations

import json
from pathlib import Path
from typing import TypedDict

import localstack.services.cloudformation.provider_utils as util
from localstack.services.cloudformation.resource_provider import (
    OperationStatus,
    ProgressEvent,
    ResourceProvider,
    ResourceRequest,
)


class OpenSearchServiceDomainProperties(TypedDict):
    AccessPolicies: dict | None
    AdvancedOptions: dict | None
    AdvancedSecurityOptions: AdvancedSecurityOptionsInput | None
    Arn: str | None
    ClusterConfig: ClusterConfig | None
    CognitoOptions: CognitoOptions | None
    DomainArn: str | None
    DomainEndpoint: str | None
    DomainEndpointOptions: DomainEndpointOptions | None
    DomainEndpoints: dict | None
    DomainName: str | None
    EBSOptions: EBSOptions | None
    EncryptionAtRestOptions: EncryptionAtRestOptions | None
    EngineVersion: str | None
    Id: str | None
    LogPublishingOptions: dict | None
    NodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions | None
    OffPeakWindowOptions: OffPeakWindowOptions | None
    ServiceSoftwareOptions: ServiceSoftwareOptions | None
    SnapshotOptions: SnapshotOptions | None
    SoftwareUpdateOptions: SoftwareUpdateOptions | None
    Tags: list[Tag] | None
    VPCOptions: VPCOptions | None


class ZoneAwarenessConfig(TypedDict):
    AvailabilityZoneCount: int | None


class ClusterConfig(TypedDict):
    DedicatedMasterCount: int | None
    DedicatedMasterEnabled: bool | None
    DedicatedMasterType: str | None
    InstanceCount: int | None
    InstanceType: str | None
    WarmCount: int | None
    WarmEnabled: bool | None
    WarmType: str | None
    ZoneAwarenessConfig: ZoneAwarenessConfig | None
    ZoneAwarenessEnabled: bool | None


class SnapshotOptions(TypedDict):
    AutomatedSnapshotStartHour: int | None


class VPCOptions(TypedDict):
    SecurityGroupIds: list[str] | None
    SubnetIds: list[str] | None


class NodeToNodeEncryptionOptions(TypedDict):
    Enabled: bool | None


class DomainEndpointOptions(TypedDict):
    CustomEndpoint: str | None
    CustomEndpointCertificateArn: str | None
    CustomEndpointEnabled: bool | None
    EnforceHTTPS: bool | None
    TLSSecurityPolicy: str | None


class CognitoOptions(TypedDict):
    Enabled: bool | None
    IdentityPoolId: str | None
    RoleArn: str | None
    UserPoolId: str | None


class MasterUserOptions(TypedDict):
    MasterUserARN: str | None
    MasterUserName: str | None
    MasterUserPassword: str | None


class Idp(TypedDict):
    EntityId: str | None
    MetadataContent: str | None


class SAMLOptions(TypedDict):
    Enabled: bool | None
    Idp: Idp | None
    MasterBackendRole: str | None
    MasterUserName: str | None
    RolesKey: str | None
    SessionTimeoutMinutes: int | None
    SubjectKey: str | None


class AdvancedSecurityOptionsInput(TypedDict):
    AnonymousAuthDisableDate: str | None
    AnonymousAuthEnabled: bool | None
    Enabled: bool | None
    InternalUserDatabaseEnabled: bool | None
    MasterUserOptions: MasterUserOptions | None
    SAMLOptions: SAMLOptions | None


class EBSOptions(TypedDict):
    EBSEnabled: bool | None
    Iops: int | None
    Throughput: int | None
    VolumeSize: int | None
    VolumeType: str | None


class EncryptionAtRestOptions(TypedDict):
    Enabled: bool | None
    KmsKeyId: str | None


class Tag(TypedDict):
    Key: str | None
    Value: str | None


class ServiceSoftwareOptions(TypedDict):
    AutomatedUpdateDate: str | None
    Cancellable: bool | None
    CurrentVersion: str | None
    Description: str | None
    NewVersion: str | None
    OptionalDeployment: bool | None
    UpdateAvailable: bool | None
    UpdateStatus: str | None


class WindowStartTime(TypedDict):
    Hours: int | None
    Minutes: int | None


class OffPeakWindow(TypedDict):
    WindowStartTime: WindowStartTime | None


class OffPeakWindowOptions(TypedDict):
    Enabled: bool | None
    OffPeakWindow: OffPeakWindow | None


class SoftwareUpdateOptions(TypedDict):
    AutoSoftwareUpdateEnabled: bool | None


REPEATED_INVOCATION = "repeated_invocation"


class OpenSearchServiceDomainProvider(ResourceProvider[OpenSearchServiceDomainProperties]):
    TYPE = "AWS::OpenSearchService::Domain"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

    def create(
        self,
        request: ResourceRequest[OpenSearchServiceDomainProperties],
    ) -> ProgressEvent[OpenSearchServiceDomainProperties]:
        """
        Create a new resource.

        Primary identifier fields:
          - /properties/DomainName



        Create-only properties:
          - /properties/DomainName

        Read-only properties:
          - /properties/Id
          - /properties/Arn
          - /properties/DomainArn
          - /properties/DomainEndpoint
          - /properties/DomainEndpoints
          - /properties/ServiceSoftwareOptions
          - /properties/AdvancedSecurityOptions/AnonymousAuthDisableDate

        IAM permissions required:
          - es:CreateDomain
          - es:DescribeDomain
          - es:AddTags
          - es:ListTags

        """
        model = request.desired_state
        opensearch_client = request.aws_client_factory.opensearch
        if not request.custom_context.get(REPEATED_INVOCATION):
            # resource is not ready
            # this is the first time this callback is invoked
            request.custom_context[REPEATED_INVOCATION] = True

            # defaults
            domain_name = model.get("DomainName")
            if not domain_name:
                domain_name = util.generate_default_name(
                    request.stack_name, request.logical_resource_id
                ).lower()[0:28]
                model["DomainName"] = domain_name

            properties = util.remove_none_values(model)
            cluster_config = properties.get("ClusterConfig")
            if isinstance(cluster_config, dict):
                # set defaults required for boto3 calls
                cluster_config.setdefault("DedicatedMasterType", "m3.medium.search")
                cluster_config.setdefault("WarmType", "ultrawarm1.medium.search")

                for key in ["DedicatedMasterCount", "InstanceCount", "WarmCount"]:
                    if key in cluster_config and isinstance(cluster_config[key], str):
                        cluster_config[key] = int(cluster_config[key])

            if properties.get("AccessPolicies"):
                properties["AccessPolicies"] = json.dumps(properties["AccessPolicies"])

            if ebs_options := properties.get("EBSOptions"):
                for key in ["Iops", "Throughput", "VolumeSize"]:
                    if key in ebs_options and isinstance(ebs_options[key], str):
                        ebs_options[key] = int(ebs_options[key])

            create_kwargs = {**util.deselect_attributes(properties, ["Tags"])}
            if tags := properties.get("Tags"):
                create_kwargs["TagList"] = tags
            opensearch_client.create_domain(**create_kwargs)
            return ProgressEvent(
                status=OperationStatus.IN_PROGRESS,
                resource_model=model,
                custom_context=request.custom_context,
            )
        opensearch_domain = opensearch_client.describe_domain(DomainName=model["DomainName"])
        if opensearch_domain["DomainStatus"]["Processing"] is False:
            # set data
            model["Arn"] = opensearch_domain["DomainStatus"]["ARN"]
            model["Id"] = opensearch_domain["DomainStatus"]["DomainId"]
            model["DomainArn"] = opensearch_domain["DomainStatus"]["ARN"]
            model["DomainEndpoint"] = opensearch_domain["DomainStatus"].get("Endpoint")
            model["DomainEndpoints"] = opensearch_domain["DomainStatus"].get("Endpoints")
            model["ServiceSoftwareOptions"] = opensearch_domain["DomainStatus"].get(
                "ServiceSoftwareOptions"
            )
            model.setdefault("AdvancedSecurityOptions", {})["AnonymousAuthDisableDate"] = (
                opensearch_domain["DomainStatus"]
                .get("AdvancedSecurityOptions", {})
                .get("AnonymousAuthDisableDate")
            )

            return ProgressEvent(status=OperationStatus.SUCCESS, resource_model=model)
        else:
            return ProgressEvent(status=OperationStatus.IN_PROGRESS, resource_model=model)

    def read(
        self,
        request: ResourceRequest[OpenSearchServiceDomainProperties],
    ) -> ProgressEvent[OpenSearchServiceDomainProperties]:
        """
        Fetch resource information

        IAM permissions required:
          - es:DescribeDomain
          - es:ListTags
        """
        raise NotImplementedError

    def delete(
        self,
        request: ResourceRequest[OpenSearchServiceDomainProperties],
    ) -> ProgressEvent[OpenSearchServiceDomainProperties]:
        """
        Delete a resource

        IAM permissions required:
          - es:DeleteDomain
          - es:DescribeDomain
        """
        opensearch_client = request.aws_client_factory.opensearch
        # TODO the delete is currently synchronous;
        #   if this changes, we should also reflect the OperationStatus here
        opensearch_client.delete_domain(DomainName=request.previous_state["DomainName"])
        return ProgressEvent(status=OperationStatus.SUCCESS, resource_model={})

    def update(
        self,
        request: ResourceRequest[OpenSearchServiceDomainProperties],
    ) -> ProgressEvent[OpenSearchServiceDomainProperties]:
        """
        Update a resource

        IAM permissions required:
          - es:UpdateDomain
          - es:UpgradeDomain
          - es:DescribeDomain
          - es:AddTags
          - es:RemoveTags
          - es:ListTags
        """
        raise NotImplementedError
