# 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 LambdaLayerVersionPermissionProperties(TypedDict):
    Action: str | None
    LayerVersionArn: str | None
    Principal: str | None
    Id: str | None
    OrganizationId: str | None


REPEATED_INVOCATION = "repeated_invocation"


class LambdaLayerVersionPermissionProvider(
    ResourceProvider[LambdaLayerVersionPermissionProperties]
):
    TYPE = "AWS::Lambda::LayerVersionPermission"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

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

        Primary identifier fields:
          - /properties/Id

        Required properties:
          - LayerVersionArn
          - Action
          - Principal

        Create-only properties:
          - /properties/OrganizationId
          - /properties/Principal
          - /properties/Action
          - /properties/LayerVersionArn

        Read-only properties:
          - /properties/Id

        """
        model = request.desired_state
        lambda_client = request.aws_client_factory.lambda_

        model["Id"] = util.generate_default_name(
            stack_name=request.stack_name, logical_resource_id=request.logical_resource_id
        )
        layer_name, version_number = self.layer_name_and_version(model)

        params = util.select_attributes(model, ["Action", "Principal"])
        params["StatementId"] = model["Id"].split("-")[-1]
        params["LayerName"] = layer_name
        params["VersionNumber"] = version_number

        lambda_client.add_layer_version_permission(**params)

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

    @staticmethod
    def layer_name_and_version(params):
        layer_arn = params.get("LayerVersionArn", "")
        parts = layer_arn.split(":")
        layer_name = parts[6] if ":" in layer_arn else layer_arn
        version_number = int(parts[7] if len(parts) > 7 else 1)  # TODO fetch latest version number
        return layer_name, version_number

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


        """
        raise NotImplementedError

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


        """
        model = request.desired_state
        lambda_client = request.aws_client_factory.lambda_

        layer_name, version_number = self.layer_name_and_version(model)
        params = {
            "StatementId": model["Id"].split("-")[-1],
            "LayerName": layer_name,
            "VersionNumber": version_number,
        }

        lambda_client.remove_layer_version_permission(**params)

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

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


        """
        raise NotImplementedError
