# LocalStack Resource Provider Scaffolding v2
from __future__ import annotations

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 RedshiftClusterProperties(TypedDict):
    ClusterType: str | None
    DBName: str | None
    MasterUserPassword: str | None
    MasterUsername: str | None
    NodeType: str | None
    AllowVersionUpgrade: bool | None
    AquaConfigurationStatus: str | None
    AutomatedSnapshotRetentionPeriod: int | None
    AvailabilityZone: str | None
    AvailabilityZoneRelocation: bool | None
    AvailabilityZoneRelocationStatus: str | None
    Classic: bool | None
    ClusterIdentifier: str | None
    ClusterParameterGroupName: str | None
    ClusterSecurityGroups: list[str] | None
    ClusterSubnetGroupName: str | None
    ClusterVersion: str | None
    DeferMaintenance: bool | None
    DeferMaintenanceDuration: int | None
    DeferMaintenanceEndTime: str | None
    DeferMaintenanceIdentifier: str | None
    DeferMaintenanceStartTime: str | None
    DestinationRegion: str | None
    ElasticIp: str | None
    Encrypted: bool | None
    Endpoint: Endpoint | None
    EnhancedVpcRouting: bool | None
    HsmClientCertificateIdentifier: str | None
    HsmConfigurationIdentifier: str | None
    IamRoles: list[str] | None
    Id: str | None
    KmsKeyId: str | None
    LoggingProperties: LoggingProperties | None
    MaintenanceTrackName: str | None
    ManualSnapshotRetentionPeriod: int | None
    NumberOfNodes: int | None
    OwnerAccount: str | None
    Port: int | None
    PreferredMaintenanceWindow: str | None
    PubliclyAccessible: bool | None
    ResourceAction: str | None
    RevisionTarget: str | None
    RotateEncryptionKey: bool | None
    SnapshotClusterIdentifier: str | None
    SnapshotCopyGrantName: str | None
    SnapshotCopyManual: bool | None
    SnapshotCopyRetentionPeriod: int | None
    SnapshotIdentifier: str | None
    Tags: list[Tag] | None
    VpcSecurityGroupIds: list[str] | None


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


class LoggingProperties(TypedDict):
    BucketName: str | None
    S3KeyPrefix: str | None


class Endpoint(TypedDict):
    Address: str | None
    Port: str | None


REPEATED_INVOCATION = "repeated_invocation"


class RedshiftClusterProvider(ResourceProvider[RedshiftClusterProperties]):
    TYPE = "AWS::Redshift::Cluster"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

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

        Primary identifier fields:
          - /properties/ClusterIdentifier

        Required properties:
          - MasterUserPassword
          - NodeType
          - MasterUsername
          - DBName
          - ClusterType

        Create-only properties:
          - /properties/ClusterIdentifier
          - /properties/OwnerAccount
          - /properties/SnapshotIdentifier
          - /properties/DBName
          - /properties/SnapshotClusterIdentifier
          - /properties/ClusterSubnetGroupName
          - /properties/MasterUsername

        Read-only properties:
          - /properties/Id
          - /properties/DeferMaintenanceIdentifier
          - /properties/Endpoint/Port
          - /properties/Endpoint/Address

        IAM permissions required:
          - redshift:DescribeClusters
          - redshift:CreateCluster
          - redshift:RestoreFromClusterSnapshot
          - redshift:EnableLogging

        """
        model = request.desired_state
        redshift = request.aws_client_factory.redshift

        if not request.custom_context.get(REPEATED_INVOCATION):
            request.custom_context[REPEATED_INVOCATION] = True

            if not model.get("ClusterIdentifier"):
                model["ClusterIdentifier"] = util.generate_default_name(
                    stack_name=request.stack_name, logical_resource_id=request.logical_resource_id
                )

            result = redshift.create_cluster(**model)
            model["Id"] = result["Cluster"]["ClusterIdentifier"]

        try:
            cluster = redshift.describe_clusters(ClusterIdentifier=model["ClusterIdentifier"])[
                "Clusters"
            ][0]
            match cluster["ClusterStatus"]:
                case "available":
                    model.setdefault("Endpoint", {})
                    model["Endpoint"]["Address"] = cluster["Endpoint"]["Address"]
                    model["Endpoint"]["Port"] = str(cluster["Endpoint"]["Port"])
                    # getting "Attribute 'DeferMaintenanceIdentifier' does not exist." on AWS
                    # model["DeferMaintenanceIdentifier"] = "?"

                    return ProgressEvent(
                        status=OperationStatus.SUCCESS,
                        resource_model=model,
                        custom_context=request.custom_context,
                    )
                case failed_state:
                    return ProgressEvent(
                        status=OperationStatus.FAILED,
                        resource_model=model,
                        custom_context=request.custom_context,
                        message=f"Cluster in failed state: {failed_state}",
                    )

        except redshift.exceptions.ClusterNotFoundFault:
            return ProgressEvent(
                status=OperationStatus.IN_PROGRESS,
                resource_model=model,
                custom_context=request.custom_context,
            )

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

        IAM permissions required:
          - redshift:DescribeClusters
          - redshift:DescribeLoggingStatus
          - redshift:DescribeSnapshotCopyGrant
          - redshift:DescribeClusterDbRevisions
        """
        raise NotImplementedError

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

        IAM permissions required:
          - redshift:DescribeClusters
          - redshift:DeleteCluster
        """
        model = request.desired_state
        redshift = request.aws_client_factory.redshift

        if not request.custom_context.get(REPEATED_INVOCATION):
            request.custom_context[REPEATED_INVOCATION] = True
            redshift.delete_cluster(ClusterIdentifier=model["ClusterIdentifier"])

        try:
            cluster = redshift.describe_clusters(ClusterIdentifier=model["ClusterIdentifier"])[
                "Clusters"
            ][0]
            match cluster["ClusterStatus"]:
                case "creating" | "modifying":
                    return ProgressEvent(
                        status=OperationStatus.FAILED,
                        resource_model=model,
                        custom_context=request.custom_context,
                        message=f"Redshift cluster in unexpected status: {cluster['ClusterStatus']}",
                    )
                case _:
                    return ProgressEvent(
                        status=OperationStatus.IN_PROGRESS,
                        resource_model=model,
                        custom_context=request.custom_context,
                    )
        except redshift.exceptions.ClusterNotFoundFault:
            return ProgressEvent(
                status=OperationStatus.SUCCESS,
                resource_model={},
                custom_context=request.custom_context,
            )

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

        IAM permissions required:
          - redshift:DescribeClusters
          - redshift:ModifyCluster
          - redshift:ModifyClusterIamRoles
          - redshift:EnableLogging
          - redshift:CreateTags
          - redshift:DeleteTags
          - redshift:DisableLogging
          - redshift:RebootCluster
          - redshift:EnableSnapshotCopy
          - redshift:DisableSnapshotCopy
          - redshift:ModifySnapshotCopyRetentionPeriod
          - redshift:ModifyAquaConfiguration
          - redshift:ResizeCluster
          - redshift:ModifyClusterMaintenance
          - redshift:DescribeClusterDbRevisions
          - redshift:ModifyClusterDbRevisions
          - redshift:PauseCluster
          - redshift:ResumeCluster
          - redshift:RotateEncryptionKey
        """
        raise NotImplementedError
