# 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 ApiGatewayDeploymentProperties(TypedDict):
    RestApiId: str | None
    DeploymentCanarySettings: DeploymentCanarySettings | None
    DeploymentId: str | None
    Description: str | None
    StageDescription: StageDescription | None
    StageName: str | None


class DeploymentCanarySettings(TypedDict):
    PercentTraffic: float | None
    StageVariableOverrides: dict | None
    UseStageCache: bool | None


class AccessLogSetting(TypedDict):
    DestinationArn: str | None
    Format: str | None


class CanarySetting(TypedDict):
    PercentTraffic: float | None
    StageVariableOverrides: dict | None
    UseStageCache: bool | None


class MethodSetting(TypedDict):
    CacheDataEncrypted: bool | None
    CacheTtlInSeconds: int | None
    CachingEnabled: bool | None
    DataTraceEnabled: bool | None
    HttpMethod: str | None
    LoggingLevel: str | None
    MetricsEnabled: bool | None
    ResourcePath: str | None
    ThrottlingBurstLimit: int | None
    ThrottlingRateLimit: float | None


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


class StageDescription(TypedDict):
    AccessLogSetting: AccessLogSetting | None
    CacheClusterEnabled: bool | None
    CacheClusterSize: str | None
    CacheDataEncrypted: bool | None
    CacheTtlInSeconds: int | None
    CachingEnabled: bool | None
    CanarySetting: CanarySetting | None
    ClientCertificateId: str | None
    DataTraceEnabled: bool | None
    Description: str | None
    DocumentationVersion: str | None
    LoggingLevel: str | None
    MethodSettings: list[MethodSetting] | None
    MetricsEnabled: bool | None
    Tags: list[Tag] | None
    ThrottlingBurstLimit: int | None
    ThrottlingRateLimit: float | None
    TracingEnabled: bool | None
    Variables: dict | None


REPEATED_INVOCATION = "repeated_invocation"


class ApiGatewayDeploymentProvider(ResourceProvider[ApiGatewayDeploymentProperties]):
    TYPE = "AWS::ApiGateway::Deployment"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

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

        Primary identifier fields:
          - /properties/DeploymentId
          - /properties/RestApiId

        Required properties:
          - RestApiId

        Create-only properties:
          - /properties/DeploymentCanarySettings
          - /properties/RestApiId

        Read-only properties:
          - /properties/DeploymentId

        IAM permissions required:
          - apigateway:POST

        """
        model = request.desired_state
        api = request.aws_client_factory.apigateway

        params = {"restApiId": model["RestApiId"]}

        if model.get("StageName"):
            params["stageName"] = model["StageName"]

        if model.get("StageDescription"):
            params["stageDescription"] = json.dumps(model["StageDescription"])

        if model.get("Description"):
            params["description"] = model["Description"]

        if model.get("DeploymentCanarySettings"):
            params["canarySettings"] = model["DeploymentCanarySettings"]

        response = api.create_deployment(**params)

        model["DeploymentId"] = response["id"]

        return ProgressEvent(
            status=OperationStatus.SUCCESS,
            resource_model=model,
            custom_context=request.custom_context,
        )

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

        IAM permissions required:
          - apigateway:GET
        """
        raise NotImplementedError

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

        IAM permissions required:
          - apigateway:GET
          - apigateway:DELETE
        """
        model = request.desired_state
        api = request.aws_client_factory.apigateway

        try:
            # TODO: verify if AWS behaves the same?
            get_stages = api.get_stages(
                restApiId=model["RestApiId"], deploymentId=model["DeploymentId"]
            )
            if stages := get_stages["item"]:
                for stage in stages:
                    api.delete_stage(restApiId=model["RestApiId"], stageName=stage["stageName"])

            api.delete_deployment(restApiId=model["RestApiId"], deploymentId=model["DeploymentId"])
        except api.exceptions.NotFoundException:
            pass

        return ProgressEvent(
            status=OperationStatus.SUCCESS,
            resource_model=model,
            custom_context=request.custom_context,
        )

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

        IAM permissions required:
          - apigateway:PATCH
          - apigateway:GET
          - apigateway:PUT
        """
        raise NotImplementedError
