# 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 ResourceGroupsGroupProperties(TypedDict):
    Name: str | None
    Arn: str | None
    Configuration: list[ConfigurationItem] | None
    Description: str | None
    ResourceQuery: ResourceQuery | None
    Resources: list[str] | None
    Tags: list[Tag] | None


class TagFilter(TypedDict):
    Key: str | None
    Values: list[str] | None


class Query(TypedDict):
    ResourceTypeFilters: list[str] | None
    StackIdentifier: str | None
    TagFilters: list[TagFilter] | None


class ResourceQuery(TypedDict):
    Query: Query | None
    Type: str | None


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


class ConfigurationParameter(TypedDict):
    Name: str | None
    Values: list[str] | None


class ConfigurationItem(TypedDict):
    Parameters: list[ConfigurationParameter] | None
    Type: str | None


REPEATED_INVOCATION = "repeated_invocation"


class ResourceGroupsGroupProvider(ResourceProvider[ResourceGroupsGroupProperties]):
    TYPE = "AWS::ResourceGroups::Group"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

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

        Primary identifier fields:
          - /properties/Name

        Required properties:
          - Name

        Create-only properties:
          - /properties/Name

        Read-only properties:
          - /properties/Arn

        IAM permissions required:
          - resource-groups:CreateGroup
          - resource-groups:Tag
          - cloudformation:DescribeStacks
          - cloudformation:ListStackResources
          - resource-groups:ListGroupResources
          - resource-groups:GroupResources

        """
        model = request.desired_state
        client = request.aws_client_factory.resource_groups

        if not model.get("Name"):
            raise ValueError("Name is a required property")

        # Default query
        resource_query = model.get("ResourceQuery", {})
        if (
            not resource_query.get("Query")
            and resource_query.get("Type") == "CLOUDFORMATION_STACK_1_0"
        ):
            resource_query["Query"] = json.dumps(
                {"ResourceTypeFilters": ["AWS::AllSupported"], "StackIdentifier": request.stack_id}
            )

        params = util.select_attributes(
            model, ["Name", "Description", "ResourceQuery", "Configuration"]
        )

        if tags := model.get("Tags"):
            params["Tags"] = util.transform_list_to_dict(tags)

        result = client.create_group(**params)
        model["Arn"] = result["Group"]["GroupArn"]

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

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

        IAM permissions required:
          - resource-groups:GetGroup
          - resource-groups:GetGroupQuery
          - resource-groups:GetTags
          - resource-groups:GetGroupConfiguration
          - resource-groups:ListGroupResources
        """
        raise NotImplementedError

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

        IAM permissions required:
          - resource-groups:DeleteGroup
          - resource-groups:UnGroupResources
        """
        client = request.aws_client_factory.resource_groups
        client.delete_group(GroupName=request.desired_state["Name"])
        return ProgressEvent(status=OperationStatus.SUCCESS, resource_model={})

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

        IAM permissions required:
          - resource-groups:UpdateGroup
          - resource-groups:GetTags
          - resource-groups:GetGroupQuery
          - resource-groups:UpdateGroupQuery
          - resource-groups:Tag
          - resource-groups:Untag
          - resource-groups:PutGroupConfiguration
          - resource-groups:GetGroupConfiguration
          - resource-groups:ListGroupResources
          - resource-groups:GroupResources
          - resource-groups:UnGroupResources
        """
        raise NotImplementedError
