# This file is automatically generated by botocraft.  Do not edit directly.
# pylint: disable=anomalous-backslash-in-string,unsubscriptable-object,line-too-long,arguments-differ,arguments-renamed,unused-import,redefined-outer-name
# pyright: reportUnusedImport=false
# mypy: disable-error-code="index, override, assignment, union-attr, misc"
from collections import OrderedDict
from datetime import datetime
from functools import cached_property
from typing import Any, ClassVar, Dict, List, Literal, Optional, Type, cast

from pydantic import Field

from botocraft.mixins.events import (DescribeRuleResponse_to_EventRule,
                                     EventRule_purge_CreatedBy_attribute,
                                     event_rules_only)
from botocraft.mixins.tags import TagsDictMixin
from botocraft.services.common import Tag

from .abstract import (Boto3Model, Boto3ModelManager, PrimaryBoto3Model,
                       ReadonlyBoto3Model, ReadonlyBoto3ModelManager,
                       ReadonlyPrimaryBoto3Model)

# ===============
# Managers
# ===============


class EventRuleManager(Boto3ModelManager):

    service_name: str = "events"

    @EventRule_purge_CreatedBy_attribute
    def create(self, model: "EventRule", Tags: Optional[List[Tag]] = None) -> str:
        """
        Creates or updates the specified rule. Rules are enabled by default, or based on value of the state. You can disable a
        rule using `DisableRule <https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DisableRule.html>`_.

        Args:
            model: The :py:class:``Rule`` to create.

        Keyword Args:
            Tags: The list of key-value pairs to associate with the rule.

        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            Name=data.get("Name"),
            ScheduleExpression=data.get("ScheduleExpression"),
            EventPattern=data.get("EventPattern"),
            State=data.get("State"),
            Description=data.get("Description"),
            RoleArn=data.get("RoleArn"),
            Tags=self.serialize(Tags),
            EventBusName=data.get("EventBusName"),
        )
        _response = self.client.put_rule(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = PutRuleResponse(**_response)

        self.sessionize(response.RuleArn)
        return cast(str, response.RuleArn)

    @EventRule_purge_CreatedBy_attribute
    def update(self, model: "EventRule", Tags: Optional[List[Tag]] = None) -> str:
        """
        Creates or updates the specified rule. Rules are enabled by default, or based on value of the state. You can disable a
        rule using `DisableRule <https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DisableRule.html>`_.

        Args:
            model: The :py:class:``Rule`` to update.

        Keyword Args:
            Tags: The list of key-value pairs to associate with the rule.

        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            Name=data.get("Name"),
            ScheduleExpression=data.get("ScheduleExpression"),
            EventPattern=data.get("EventPattern"),
            State=data.get("State"),
            Description=data.get("Description"),
            RoleArn=data.get("RoleArn"),
            Tags=self.serialize(Tags),
            EventBusName=data.get("EventBusName"),
        )
        _response = self.client.put_rule(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = PutRuleResponse(**_response)

        self.sessionize(response.RuleArn)
        return cast(str, response.RuleArn)

    def delete(
        self, Name: str, *, EventBusName: Optional[str] = None, Force: bool = True
    ) -> None:
        """
        Deletes the specified rule.

        Args:
            Name: The name of the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
            Force: If this is a managed rule, created by an Amazon Web Services service on your behalf, you must specify
                ``Force`` as ``True`` to delete the rule. This parameter is ignored for rules that are not managed rules. You can
                check whether a rule is a managed rule by using ``DescribeRule`` or ``ListRules`` and checking the ``ManagedBy``
                field of the response.
        """
        args: Dict[str, Any] = dict(
            Name=self.serialize(Name),
            EventBusName=self.serialize(EventBusName),
            Force=self.serialize(Force),
        )
        self.client.delete_rule(**{k: v for k, v in args.items() if v is not None})

    @DescribeRuleResponse_to_EventRule
    def get(
        self, Name: str, *, EventBusName: Optional[str] = None
    ) -> Optional["DescribeRuleResponse"]:
        """
        Describes the specified rule.

        Args:
            Name: The name of the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
        """
        args: Dict[str, Any] = dict(
            Name=self.serialize(Name), EventBusName=self.serialize(EventBusName)
        )
        _response = self.client.describe_rule(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeRuleResponse(**_response)

        if response:
            self.sessionize(response)
            return response
        return None

    def list(
        self,
        *,
        NamePrefix: Optional[str] = None,
        EventBusName: Optional[str] = None,
        Limit: Optional[int] = None
    ) -> List["EventRule"]:
        """
        Lists your Amazon EventBridge rules. You can either list all the rules or you can provide a prefix to match to
        the rule names.

        Keyword Args:
            NamePrefix: The prefix matching the rule name.
            EventBusName: The name or ARN of the event bus to list the rules for. If you omit this, the default event bus is
                used.
            Limit: The maximum number of results to return.
        """
        paginator = self.client.get_paginator("list_rules")
        args: Dict[str, Any] = dict(
            NamePrefix=self.serialize(NamePrefix),
            EventBusName=self.serialize(EventBusName),
            Limit=self.serialize(Limit),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results: List["EventRule"] = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListRulesResponse(**_response)
            if response.Rules:
                results.extend(response.Rules)
            else:
                break
        self.sessionize(results)
        return results

    @event_rules_only
    def list_by_target(
        self,
        TargetArn: str,
        *,
        EventBusName: Optional[str] = None,
        Limit: Optional[int] = None
    ) -> List[str]:
        """
        Lists the rules for the specified target. You can see which of the rules in Amazon EventBridge can invoke a
        specific target in your account.

        Args:
            TargetArn: The Amazon Resource Name (ARN) of the target resource.

        Keyword Args:
            EventBusName: The name or ARN of the event bus to list rules for. If you omit this, the default event bus is used.
            Limit: The maximum number of results to return.
        """
        paginator = self.client.get_paginator("list_rule_names_by_target")
        args: Dict[str, Any] = dict(
            TargetArn=self.serialize(TargetArn),
            EventBusName=self.serialize(EventBusName),
            Limit=self.serialize(Limit),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )

        results: List[str] = []

        for _response in response_iterator:
            response = ListRuleNamesByTargetResponse(**_response)
            if response.RuleNames is not None:
                results.extend(response.RuleNames)
            else:
                break

        self.sessionize(results)
        return cast(List[str], results)

    def list_targets(
        self,
        Rule: str,
        *,
        EventBusName: Optional[str] = None,
        Limit: Optional[int] = None
    ) -> List["EventTarget"]:
        """
        Lists the targets assigned to the specified rule.

        Args:
            Rule: The name of the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
            Limit: The maximum number of results to return.
        """
        paginator = self.client.get_paginator("list_targets_by_rule")
        args: Dict[str, Any] = dict(
            Rule=self.serialize(Rule),
            EventBusName=self.serialize(EventBusName),
            Limit=self.serialize(Limit),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )

        results: List["EventTarget"] = []

        for _response in response_iterator:
            response = ListTargetsByRuleResponse(**_response)
            if response.Targets is not None:
                results.extend(response.Targets)
            else:
                break

        self.sessionize(results)
        return cast(List["EventTarget"], results)

    def enable(self, Name: str, *, EventBusName: Optional[str] = None) -> None:
        """
        Enables the specified rule. If the rule does not exist, the operation fails.

        Args:
            Name: The name of the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
        """
        args: Dict[str, Any] = dict(
            Name=self.serialize(Name), EventBusName=self.serialize(EventBusName)
        )
        self.client.enable_rule(**{k: v for k, v in args.items() if v is not None})

    def disable(self, Name: str, *, EventBusName: Optional[str] = None) -> None:
        """
        Disables the specified rule. A disabled rule won't match any events, and won't self-trigger if it has a schedule
        expression.

        Args:
            Name: The name of the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
        """
        args: Dict[str, Any] = dict(
            Name=self.serialize(Name), EventBusName=self.serialize(EventBusName)
        )
        self.client.disable_rule(**{k: v for k, v in args.items() if v is not None})


class EventTargetManager(Boto3ModelManager):

    service_name: str = "events"

    def create(
        self, model: "EventTarget", EventBusName: Optional[str] = None
    ) -> "PutTargetsResponse":
        """
        Adds the specified targets to the specified rule, or updates the targets if they are already associated with the
        rule.

        Args:
            model: The :py:class:``Target`` to create.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            Rule=data.get("Rule"),
            Targets=data.get("Targets"),
            EventBusName=self.serialize(EventBusName),
        )
        _response = self.client.put_targets(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = PutTargetsResponse(**_response)

        self.sessionize(response)
        return cast("PutTargetsResponse", response)

    def update(
        self, model: "EventTarget", EventBusName: Optional[str] = None
    ) -> "PutTargetsResponse":
        """
        Adds the specified targets to the specified rule, or updates the targets if they are already associated with the
        rule.

        Args:
            model: The :py:class:``Target`` to update.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            Rule=data.get("Rule"),
            Targets=data.get("Targets"),
            EventBusName=self.serialize(EventBusName),
        )
        _response = self.client.put_targets(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = PutTargetsResponse(**_response)

        self.sessionize(response)
        return cast("PutTargetsResponse", response)

    def delete(
        self,
        Rule: str,
        Ids: List[str],
        *,
        EventBusName: Optional[str] = None,
        Force: Optional[bool] = None
    ) -> "Target":
        """
        Removes the specified targets from the specified rule. When the rule is triggered, those targets are no longer
        be invoked.

        Args:
            Rule: The name of the rule.
            Ids: The IDs of the targets to remove from the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
            Force: If this is a managed rule, created by an Amazon Web Services service on your behalf, you must specify
                ``Force`` as ``True`` to remove targets. This parameter is ignored for rules that are not managed rules. You can
                check whether a rule is a managed rule by using ``DescribeRule`` or ``ListRules`` and checking the ``ManagedBy``
                field of the response.
        """
        args: Dict[str, Any] = dict(
            Rule=self.serialize(Rule),
            Ids=self.serialize(Ids),
            EventBusName=self.serialize(EventBusName),
            Force=self.serialize(Force),
        )
        _response = self.client.remove_targets(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = RemoveTargetsResponse(**_response)
        return response

    def list(
        self,
        Rule: str,
        *,
        EventBusName: Optional[str] = None,
        Limit: Optional[int] = None
    ) -> List["EventTarget"]:
        """
        Lists the targets assigned to the specified rule.

        Args:
            Rule: The name of the rule.

        Keyword Args:
            EventBusName: The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is
                used.
            Limit: The maximum number of results to return.
        """
        paginator = self.client.get_paginator("list_targets_by_rule")
        args: Dict[str, Any] = dict(
            Rule=self.serialize(Rule),
            EventBusName=self.serialize(EventBusName),
            Limit=self.serialize(Limit),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results: List["EventTarget"] = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListTargetsByRuleResponse(**_response)
            if response.Targets:
                results.extend(response.Targets)
            else:
                break
        self.sessionize(results)
        return results

    @event_rules_only
    def list_rules(
        self,
        TargetArn: str,
        *,
        EventBusName: Optional[str] = None,
        Limit: Optional[int] = None
    ) -> List[str]:
        """
        Lists the rules for the specified target. You can see which of the rules in Amazon EventBridge can invoke a
        specific target in your account.

        Args:
            TargetArn: The Amazon Resource Name (ARN) of the target resource.

        Keyword Args:
            EventBusName: The name or ARN of the event bus to list rules for. If you omit this, the default event bus is used.
            Limit: The maximum number of results to return.
        """
        paginator = self.client.get_paginator("list_rule_names_by_target")
        args: Dict[str, Any] = dict(
            TargetArn=self.serialize(TargetArn),
            EventBusName=self.serialize(EventBusName),
            Limit=self.serialize(Limit),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )

        results: List[str] = []

        for _response in response_iterator:
            response = ListRuleNamesByTargetResponse(**_response)
            if response.RuleNames is not None:
                results.extend(response.RuleNames)
            else:
                break

        self.sessionize(results)
        return cast(List[str], results)


# ==============
# Service Models
# ==============


class EventRule(PrimaryBoto3Model):
    """
    Contains information about a rule in Amazon EventBridge.
    """

    manager_class: ClassVar[Type[Boto3ModelManager]] = EventRuleManager

    Name: Optional[str] = None
    """
    The name of the rule.
    """
    Arn: str = Field(default=None, frozen=True)
    """
    The Amazon Resource Name (ARN) of the rule.
    """
    EventPattern: Optional[str] = None
    """
    The event pattern of the rule.

    For more information, see
    `Events and Event Patterns <https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-and-event-patterns.html>`_
    in the  **Amazon
    EventBridge User Guide** .
    """
    State: Optional[
        Literal["ENABLED", "DISABLED", "ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS"]
    ] = None
    """
    The state of the rule.
    """
    Description: Optional[str] = None
    """
    The description of the rule.
    """
    ScheduleExpression: Optional[str] = None
    """
    The scheduling expression.

    For example, "cron(0 20 * * ? *)", "rate(5 minutes)". For more information, see
    `Creating an Amazon EventBridge rule that runs on a schedule <https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-
    rule-schedule.html>`_.
    """
    RoleArn: Optional[str] = None
    """
    The Amazon Resource Name (ARN) of the role that is used for target invocation.
    """
    ManagedBy: str = Field(default=None, frozen=True)
    """
    If the rule was created on behalf of your account by an Amazon Web Services service, this field displays the
    principal name of the service that created the rule.
    """
    EventBusName: Optional[str] = None
    """
    The name or ARN of the event bus associated with the rule.

    If you omit this, the default event bus is used.
    """
    CreatedBy: Optional[Optional[str]] = None

    @property
    def pk(self) -> Optional[str]:
        """
        Return the primary key of the model.   This is the value of the :py:attr:`Name` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.Name

    @property
    def arn(self) -> Optional[str]:
        """
        Return the ARN of the model.   This is the value of the :py:attr:`Arn` attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.Arn

    @property
    def name(self) -> Optional[str]:
        """
        Return the name of the model.   This is the value of the :py:attr:`Name` attribute.

        Returns:
            The name of the model instance.
        """
        return self.Name

    @cached_property
    def targets(self) -> Optional[List["EventTarget"]]:
        """
        Return the targets that are associated with this rule, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "Rule": self.Name,
                }
            )
        except AttributeError:
            return []
        return EventTarget.objects.using(self.session).list(**pk)  # type: ignore[arg-type]

    def enable(self) -> "None":
        """
        Enable the rule.
        """

        return (
            cast(EventRuleManager, self.objects)
            .using(self.session)
            .enable(
                cast(str, self.Name),
            )
        )

    def disable(self) -> "None":
        """
        Disable the rule.
        """

        return (
            cast(EventRuleManager, self.objects)
            .using(self.session)
            .disable(
                cast(str, self.Name),
            )
        )


class EventsInputTransformer(Boto3Model):
    """
    Settings to enable you to provide custom input to a target based on certain event data.

    You can extract one or more key-value pairs from the event and then use that data to send customized input to the
    target.
    """

    InputPathsMap: Optional[Dict[str, str]] = None
    """
    Map of JSON paths to be extracted from the event.

    You can then insert these in the template in ``InputTemplate`` to
    produce the output you want to be sent to the target.
    """
    InputTemplate: str
    """
    Input template where you specify placeholders that will be filled with the values of the keys from ``InputPathsMap``
    to customize the data sent to the target.

    Enclose each ``InputPathsMaps`` value in brackets: <*value*>
    """


class EventsKinesisParameters(Boto3Model):
    """
    The custom parameter you can use to control the shard assignment, when the target is a Kinesis data stream.

    If you do
    not include this parameter, the default is to use the ``eventId`` as the partition key.
    """

    PartitionKeyPath: str
    """
    The JSON path to be extracted from the event and used as the partition key.

    For more information, see
    `Amazon Kinesis Streams Key Concepts <https://docs.aws.amazon.com/streams/latest/dev/key-concepts.html#partition-key>`_
    in the *Amazon
    Kinesis Streams Developer Guide*.
    """


class RunCommandTarget(Boto3Model):
    """
    Information about the EC2 instances that are to be sent the command, specified as key-value pairs.

    Each
    ``RunCommandTarget`` block can include only one key, but this key may specify multiple values.
    """

    Key: str
    """
    Can be either ``tag:`` *tag-key* or ``InstanceIds``.
    """
    Values: List[str]
    """
    If ``Key`` is ``tag:`` *tag-key*, ``Values`` is a list of tag values.

    If ``Key`` is ``InstanceIds``, ``Values`` is a
    list of Amazon EC2 instance IDs.
    """


class EventsRunCommandParameters(Boto3Model):
    """
    Parameters used when you are using the rule to invoke Amazon EC2 Run Command.
    """

    RunCommandTargets: List["RunCommandTarget"]
    """
    Currently, we support including only one RunCommandTarget block, which specifies either an array of InstanceIds or a
    tag.
    """


class EventsAwsVpcConfiguration(Boto3Model):
    """
    Use this structure to specify the VPC subnets and security groups for the task, and whether a public IP address is
    to be used.

    This structure is relevant only for ECS tasks that use the ``awsvpc`` network mode.
    """

    Subnets: List[str]
    """
    Specifies the subnets associated with the task.

    These subnets must all be in the same VPC. You can specify as many as 16 subnets.
    """
    SecurityGroups: Optional[List[str]] = None
    """
    Specifies the security groups associated with the task.

    These security groups must all be in the same VPC. You can specify as many as five security groups. If you do not
    specify a security group, the default security group for the VPC is used.
    """
    AssignPublicIp: Optional[Literal["ENABLED", "DISABLED"]] = None
    """
    Specifies whether the task's elastic network interface receives a public IP address.

    You can specify ``ENABLED`` only
    when ``LaunchType`` in ``EcsParameters`` is set to ``FARGATE``.
    """


class EventsNetworkConfiguration(Boto3Model):
    """
    Use this structure if the Amazon ECS task uses the ``awsvpc`` network mode. This structure specifies the VPC subnets
    and security groups associated with the task, and whether a public IP address is to be used. This structure is
    required if ``LaunchType`` is ``FARGATE`` because the ``awsvpc`` mode is required for Fargate tasks.

    If you specify ``NetworkConfiguration`` when the target ECS task does not use the ``awsvpc`` network mode, the task
    fails.
    """

    awsvpcConfiguration: Optional[EventsAwsVpcConfiguration] = None
    """
    Use this structure to specify the VPC subnets and security groups for the task, and whether a public IP address is
    to be used.

    This structure is relevant only for ECS tasks that use the ``awsvpc`` network mode.
    """


class EventsCapacityProviderStrategyItem(Boto3Model):
    """
    The details of a capacity provider strategy.

    To learn more, see `CapacityProviderStrategyItem <https://docs.aws.amazon.c
    om/AmazonECS/latest/APIReference/API_CapacityProviderStrategyItem.html>`_ in the Amazon ECS API Reference.
    """

    capacityProvider: str
    """
    The short name of the capacity provider.
    """
    weight: Optional[int] = None
    """
    The weight value designates the relative percentage of the total number of tasks launched that should use the
    specified capacity provider.

    The weight value is taken into consideration after the base value, if defined, is satisfied.
    """
    base: Optional[int] = None
    """
    The base value designates how many tasks, at a minimum, to run on the specified capacity provider.

    Only one capacity provider in a capacity provider strategy can have a base defined. If no value is specified, the
    default value of 0 is used.
    """


class EventsPlacementConstraint(Boto3Model):
    """
    An object representing a constraint on task placement.

    To learn more, see
    `Task Placement Constraints <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html>`_
    in the Amazon
    Elastic Container Service Developer Guide.
    """

    type: Optional[Literal["distinctInstance", "memberOf"]] = None
    """
    The type of constraint.

    Use distinctInstance to ensure that each task in a particular group is running on a different container instance.
    Use memberOf to restrict the selection to a group of valid candidates.
    """
    expression: Optional[str] = None
    """
    A cluster query language expression to apply to the constraint.

    You cannot specify an expression if the constraint type
    is ``distinctInstance``. To learn more, see `Cluster Query
    Language <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query-language.html>`_ in the Amazon Elastic
    Container Service Developer Guide.
    """


class EventsPlacementStrategy(Boto3Model):
    """
    The task placement strategy for a task or service.

    To learn more, see
    `Task Placement Strategies <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html>`_
    in the Amazon
    Elastic Container Service Service Developer Guide.
    """

    type: Optional[Literal["random", "spread", "binpack"]] = None
    """
    The type of placement strategy.

    The random placement strategy randomly places tasks on available candidates. The spread placement strategy spreads
    placement across available candidates evenly based on the field parameter. The binpack strategy places tasks on
    available candidates that have the least available amount of the resource that is specified with the field
    parameter. For example, if you binpack on memory, a task is placed on the instance with the least amount of
    remaining memory (but still enough to run the task).
    """
    field: Optional[str] = None
    """
    The field to apply the placement strategy against.

    For the spread placement strategy, valid values are instanceId (or host, which has the same effect), or any platform
    or custom attribute that is applied to a container instance, such as attribute:ecs.availability-zone. For the
    binpack placement strategy, valid values are cpu and memory. For the random placement strategy, this field is not
    used.
    """


class EventsEcsParameters(TagsDictMixin, Boto3Model):
    """
    Contains the Amazon ECS task definition and task count to be used, if the event target is an Amazon ECS task.

    For more information about Amazon ECS tasks, see
    `Task Definitions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html>`_
    in the *Amazon EC2
    Container Service Developer Guide*.
    """

    tag_class: ClassVar[Type] = Tag
    TaskDefinitionArn: str
    """
    The ARN of the task definition to use if the event target is an Amazon ECS task.
    """
    TaskCount: Optional[int] = None
    """
    The number of tasks to create based on ``TaskDefinition``.

    The default is 1.
    """
    LaunchType: Optional[Literal["EC2", "FARGATE", "EXTERNAL"]] = None
    """
    Specifies the launch type on which your task is running.

    The launch type that you specify here must match one of the
    launch type (compatibilities) of the target task. The ``FARGATE`` value is supported only in the Regions where Fargate
    with Amazon ECS is supported. For more information, see `Fargate on Amazon
    ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS-Fargate.html>`_ in the *Amazon Elastic Container
    Service Developer Guide*.
    """
    NetworkConfiguration: Optional[EventsNetworkConfiguration] = None
    """
    Use this structure if the Amazon ECS task uses the ``awsvpc`` network mode.

    This structure specifies the VPC subnets and
    security groups associated with the task, and whether a public IP address is to be used. This structure is required if
    ``LaunchType`` is ``FARGATE`` because the ``awsvpc`` mode is required for Fargate tasks.
    """
    PlatformVersion: Optional[str] = None
    """
    Specifies the platform version for the task.

    Specify only the numeric portion of the platform version, such as
    ``1.1.0``.
    """
    Group: Optional[str] = None
    """
    Specifies an ECS task group for the task.

    The maximum length is 255 characters.
    """
    CapacityProviderStrategy: Optional[List["EventsCapacityProviderStrategyItem"]] = (
        None
    )
    """
    The capacity provider strategy to use for the task.
    """
    EnableECSManagedTags: Optional[bool] = None
    """
    Specifies whether to enable Amazon ECS managed tags for the task.

    For more information, see
    `Tagging Your Amazon ECS Resources <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html>`_
    in the Amazon Elastic
    Container Service Developer Guide.
    """
    EnableExecuteCommand: Optional[bool] = None
    """
    Whether or not to enable the execute command functionality for the containers in this task.

    If true, this enables execute command functionality on all containers in the task.
    """
    PlacementConstraints: Optional[List["EventsPlacementConstraint"]] = None
    """
    An array of placement constraint objects to use for the task.

    You can specify up to 10 constraints per task (including constraints in the task definition and those specified at
    runtime).
    """
    PlacementStrategy: Optional[List["EventsPlacementStrategy"]] = None
    """
    The placement strategy objects to use for the task.

    You can specify a maximum of five strategy rules per task.
    """
    PropagateTags: Optional[Literal["TASK_DEFINITION"]] = None
    """
    Specifies whether to propagate the tags from the task definition to the task.

    If no value is specified, the tags are not propagated. Tags can only be propagated to the task during task creation.
    To add tags to a task after task creation, use the TagResource API action.
    """
    ReferenceId: Optional[str] = None
    """
    The reference ID to use for the task.
    """
    Tags: Optional[List[Tag]] = None
    """
    The metadata that you apply to the task to help you categorize and organize them.

    Each tag consists of a key and an optional value, both of which you define. To learn more, see
    `RunTask <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html#ECS-RunTask-request-tags>`_
    in the
    Amazon ECS API Reference.
    """


class BatchArrayProperties(Boto3Model):
    """
    The array properties for the submitted job, such as the size of the array.

    The array size can be between 2 and 10,000. If you specify array properties for a job, it becomes an array job. This
    parameter is used only if the target is an Batch job.
    """

    Size: Optional[int] = None
    """
    The size of the array, if this is an array batch job.

    Valid values are integers between 2 and 10,000.
    """


class BatchRetryStrategy(Boto3Model):
    """
    The retry strategy to use for failed jobs, if the target is an Batch job.

    The retry strategy is the number of times to retry the failed job execution. Valid values are 1-10. When you specify
    a retry strategy here, it overrides the retry strategy defined in the job definition.
    """

    Attempts: Optional[int] = None
    """
    The number of times to attempt to retry, if the job fails.

    Valid values are 1-10.
    """


class EventsBatchParameters(Boto3Model):
    """
    If the event target is an Batch job, this contains the job definition, job name, and other parameters.

    For more
    information, see `Jobs <https://docs.aws.amazon.com/batch/latest/userguide/jobs.html>`_ in the *Batch User Guide*.
    """

    JobDefinition: str
    """
    The ARN or name of the job definition to use if the event target is an Batch job.

    This job definition must already exist.
    """
    JobName: str
    """
    The name to use for this execution of the job, if the target is an Batch job.
    """
    ArrayProperties: Optional[BatchArrayProperties] = None
    """
    The array properties for the submitted job, such as the size of the array.

    The array size can be between 2 and 10,000. If you specify array properties for a job, it becomes an array job. This
    parameter is used only if the target is an Batch job.
    """
    RetryStrategy: Optional[BatchRetryStrategy] = None
    """
    The retry strategy to use for failed jobs, if the target is an Batch job.

    The retry strategy is the number of times to retry the failed job execution. Valid values are 1-10. When you specify
    a retry strategy here, it overrides the retry strategy defined in the job definition.
    """


class EventsSqsParameters(Boto3Model):
    """
    Contains the message group ID to use when the target is a FIFO queue.

    If you specify an SQS FIFO queue as a target, the queue must have content-based deduplication enabled.
    """

    MessageGroupId: Optional[str] = None
    """
    The FIFO message group ID to use as the target.
    """


class EventsHttpParameters(Boto3Model):
    """
    Contains the HTTP parameters to use when the target is a API Gateway endpoint or EventBridge ApiDestination.

    If you specify an API Gateway API or EventBridge ApiDestination as a target, you can use this parameter to specify
    headers, path parameters, and query string keys/values as part of your target invoking request. If you're using
    ApiDestinations, the corresponding Connection can also have these values configured. In case of any conflicting
    keys, values from the Connection take precedence.
    """

    PathParameterValues: Optional[List[str]] = None
    """
    The path parameter values to be used to populate API Gateway API or EventBridge ApiDestination path wildcards ("*").
    """
    HeaderParameters: Optional[Dict[str, str]] = None
    """
    The headers that need to be sent as part of request invoking the API Gateway API or EventBridge ApiDestination.
    """
    QueryStringParameters: Optional[Dict[str, str]] = None
    """
    The query string keys/values that need to be sent as part of request invoking the API Gateway API or EventBridge
    ApiDestination.
    """


class EventsRedshiftDataParameters(Boto3Model):
    """
    Contains the Amazon Redshift Data API parameters to use when the target is a Amazon Redshift cluster.

    If you specify a Amazon Redshift Cluster as a Target, you can use this to specify parameters to invoke the Amazon
    Redshift Data API ExecuteStatement based on EventBridge events.
    """

    SecretManagerArn: Optional[str] = None
    """
    The name or ARN of the secret that enables access to the database.

    Required when authenticating using Amazon Web Services Secrets Manager.
    """
    Database: str
    """
    The name of the database.

    Required when authenticating using temporary credentials.
    """
    DbUser: Optional[str] = None
    """
    The database user name.

    Required when authenticating using temporary credentials.
    """
    Sql: Optional[str] = None
    """
    The SQL statement text to run.
    """
    StatementName: Optional[str] = None
    """
    The name of the SQL statement.

    You can name the SQL statement when you create it to identify the query.
    """
    WithEvent: Optional[bool] = None
    """
    Indicates whether to send an event back to EventBridge after the SQL statement runs.
    """
    Sqls: Optional[List[str]] = None
    """
    One or more SQL statements to run.

    The SQL statements are run as a single transaction. They run serially in the order of the array. Subsequent SQL
    statements don't start until the previous statement in the array completes. If any SQL statement fails, then because
    they are run as one transaction, all work is rolled back.
    """


class SageMakerPipelineParameter(Boto3Model):
    """
    Name/Value pair of a parameter to start execution of a SageMaker Model Building Pipeline.
    """

    Name: str
    """
    Name of parameter to start execution of a SageMaker Model Building Pipeline.
    """
    Value: str
    """
    Value of parameter to start execution of a SageMaker Model Building Pipeline.
    """


class EventsSageMakerPipelineParameters(Boto3Model):
    """
    Contains the SageMaker Model Building Pipeline parameters to start execution of a SageMaker Model Building Pipeline.

    If you specify a SageMaker Model Building Pipeline as a target, you can use this to specify parameters to start a
    pipeline execution based on EventBridge events.
    """

    PipelineParameterList: Optional[List["SageMakerPipelineParameter"]] = None
    """
    List of Parameter names and values for SageMaker Model Building Pipeline execution.
    """


class EventsDeadLetterConfig(Boto3Model):
    """
    The ``DeadLetterConfig`` that defines the target queue to send dead-letter queue events to.
    """

    Arn: Optional[str] = None
    """
    The ARN of the SQS queue specified as the target for the dead-letter queue.
    """


class EventsRetryPolicy(Boto3Model):
    """
    The ``RetryPolicy`` object that contains the retry policy configuration to use for the dead-letter queue.
    """

    MaximumRetryAttempts: Optional[int] = None
    """
    The maximum number of retry attempts to make before the request fails.

    Retry attempts continue until either the maximum
    number of attempts is made or until the duration of the ``MaximumEventAgeInSeconds`` is met.
    """
    MaximumEventAgeInSeconds: Optional[int] = None
    """
    The maximum amount of time, in seconds, to continue to make retry attempts.
    """


class EventsAppSyncParameters(Boto3Model):
    """
    Contains the GraphQL operation to be parsed and executed, if the event target is an AppSync API.
    """

    GraphQLOperation: Optional[str] = None
    """
    The GraphQL operation; that is, the query, mutation, or subscription to be parsed and executed by the GraphQL
    service.
    """


class EventTarget(PrimaryBoto3Model):
    """Targets are the resources to be invoked when a rule is triggered. For a complete list of services and resources that can
    be set as a target, see `PutTargets <https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutTargets.html>`_.

    If you are setting the event bus of another account as the target, and that account granted permission to your account
    through an organization instead of directly by the account ID, then you must specify a ``RoleArn`` with proper
    permissions in the ``Target`` structure. For more information, see `Sending and Receiving Events Between Amazon Web
    Services Accounts <https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-
    delivery.html>`_ in the *Amazon EventBridge User Guide*.

    """

    manager_class: ClassVar[Type[Boto3ModelManager]] = EventTargetManager

    Id: str = Field(frozen=True)
    """
    The ID of the target within the specified rule.

    Use this ID to reference the target when updating the rule. We recommend using a memorable and unique string.
    """
    Arn: str = Field(frozen=True)
    """
    The Amazon Resource Name (ARN) of the target.
    """
    RoleArn: str = Field(default=None, frozen=True)
    """
    The Amazon Resource Name (ARN) of the IAM role to be used for this target when the rule is triggered.

    If one rule triggers multiple targets, you can use a different IAM role for each target.
    """
    Input: str = Field(default=None, frozen=True)
    """
    Valid JSON text passed to the target.

    In this case, nothing from the event itself is passed to the target. For more
    information, see `The JavaScript Object Notation (JSON) Data Interchange Format <http://www.rfc-
    editor.org/rfc/rfc7159.txt>`_.
    """
    InputPath: str = Field(default=None, frozen=True)
    """
    The value of the JSONPath that is used for extracting part of the matched event when passing it to the target.

    You may use JSON dot notation or bracket notation. For more information about JSON paths, see
    `JSONPath <http://goessner.net/articles/JsonPath/>`_.
    """
    InputTransformer: EventsInputTransformer = Field(default=None, frozen=True)
    """
    Settings to enable you to provide custom input to a target based on certain event data.

    You can extract one or more key-value pairs from the event and then use that data to send customized input to the
    target.
    """
    KinesisParameters: EventsKinesisParameters = Field(default=None, frozen=True)
    """
    The custom parameter you can use to control the shard assignment, when the target is a Kinesis data stream.

    If you do
    not include this parameter, the default is to use the ``eventId`` as the partition key.
    """
    RunCommandParameters: EventsRunCommandParameters = Field(default=None, frozen=True)
    """
    Parameters used when you are using the rule to invoke Amazon EC2 Run Command.
    """
    EcsParameters: EventsEcsParameters = Field(default=None, frozen=True)
    """
    Contains the Amazon ECS task definition and task count to be used, if the event target is an Amazon ECS task.

    For more information about Amazon ECS tasks, see
    `Task Definitions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html>`_
    in the *Amazon EC2
    Container Service Developer Guide*.
    """
    BatchParameters: EventsBatchParameters = Field(default=None, frozen=True)
    """
    If the event target is an Batch job, this contains the job definition, job name, and other parameters.

    For more
    information, see `Jobs <https://docs.aws.amazon.com/batch/latest/userguide/jobs.html>`_ in the *Batch User Guide*.
    """
    SqsParameters: EventsSqsParameters = Field(default=None, frozen=True)
    """
    Contains the message group ID to use when the target is a FIFO queue.
    """
    HttpParameters: EventsHttpParameters = Field(default=None, frozen=True)
    """
    Contains the HTTP parameters to use when the target is a API Gateway endpoint or EventBridge ApiDestination.
    """
    RedshiftDataParameters: EventsRedshiftDataParameters = Field(
        default=None, frozen=True
    )
    """
    Contains the Amazon Redshift Data API parameters to use when the target is a Amazon Redshift cluster.
    """
    SageMakerPipelineParameters: EventsSageMakerPipelineParameters = Field(
        default=None, frozen=True
    )
    """
    Contains the SageMaker Model Building Pipeline parameters to start execution of a SageMaker Model Building Pipeline.
    """
    DeadLetterConfig: EventsDeadLetterConfig = Field(default=None, frozen=True)
    """
    The ``DeadLetterConfig`` that defines the target queue to send dead-letter queue events to.
    """
    RetryPolicy: EventsRetryPolicy = Field(default=None, frozen=True)
    """
    The ``RetryPolicy`` object that contains the retry policy configuration to use for the dead-letter queue.
    """
    AppSyncParameters: EventsAppSyncParameters = Field(default=None, frozen=True)
    """
    Contains the GraphQL operation to be parsed and executed, if the event target is an AppSync API.
    """

    @property
    def pk(self) -> Optional[str]:
        """
        Return the primary key of the model.   This is the value of the :py:attr:`Id` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.Id

    @property
    def arn(self) -> Optional[str]:
        """
        Return the ARN of the model.   This is the value of the :py:attr:`Arn` attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.Arn

    @property
    def name(self) -> Optional[str]:
        """
        Return the name of the model.   This is the value of the :py:attr:`Id` attribute.

        Returns:
            The name of the model instance.
        """
        return self.Id

    @cached_property
    def rules(self) -> Optional["EventRule"]:
        """
        Return the :py:class:`Rule` object that this target belongs to.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "TargetArn": self.Arn,
                }
            )
        except AttributeError:
            return None
        return EventRule.objects.using(self.session).list_by_target(**pk)  # type: ignore[arg-type]


# =======================
# Request/Response Models
# =======================


class PutRuleResponse(Boto3Model):
    RuleArn: Optional[str] = None
    """
    The Amazon Resource Name (ARN) of the rule.
    """


class DescribeRuleResponse(Boto3Model):
    Name: Optional[str] = None
    """
    The name of the rule.
    """
    Arn: Optional[str] = None
    """
    The Amazon Resource Name (ARN) of the rule.
    """
    EventPattern: Optional[str] = None
    """
    The event pattern.

    For more information, see
    `Events and Event Patterns <https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-and-event-patterns.html>`_
    in the  **Amazon
    EventBridge User Guide** .
    """
    ScheduleExpression: Optional[str] = None
    """
    The scheduling expression.

    For example, "cron(0 20 * * ? *)", "rate(5 minutes)".
    """
    State: Optional[
        Literal["ENABLED", "DISABLED", "ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS"]
    ] = None
    """
    Specifies whether the rule is enabled or disabled.
    """
    Description: Optional[str] = None
    """
    The description of the rule.
    """
    RoleArn: Optional[str] = None
    """
    The Amazon Resource Name (ARN) of the IAM role associated with the rule.
    """
    ManagedBy: Optional[str] = None
    """
    If this is a managed rule, created by an Amazon Web Services service on your behalf, this field displays the
    principal name of the Amazon Web Services service that created the rule.
    """
    EventBusName: Optional[str] = None
    """
    The name of the event bus associated with the rule.
    """
    CreatedBy: Optional[str] = None
    """
    The account ID of the user that created the rule.

    If you use ``PutRule`` to put a rule on an event bus in another
    account, the other account is the owner of the rule, and the rule ARN includes the account ID for that account. However,
    the value for ``CreatedBy`` is the account ID as the account that created the rule in the other account.
    """


class ListRulesResponse(Boto3Model):
    Rules: Optional[List["EventRule"]] = None
    """
    The rules that match the specified criteria.
    """
    NextToken: Optional[str] = None
    """
    Indicates whether there are additional results to retrieve.

    If there are no more results, the value is null.
    """


class ListRuleNamesByTargetResponse(Boto3Model):
    RuleNames: Optional[List[str]] = None
    """
    The names of the rules that can invoke the given target.
    """
    NextToken: Optional[str] = None
    """
    Indicates whether there are additional results to retrieve.

    If there are no more results, the value is null.
    """


class ListTargetsByRuleResponse(Boto3Model):
    Targets: Optional[List["EventTarget"]] = None
    """
    The targets assigned to the rule.
    """
    NextToken: Optional[str] = None
    """
    Indicates whether there are additional results to retrieve.

    If there are no more results, the value is null.
    """


class PutTargetsResultEntry(Boto3Model):
    """
    Represents a target that failed to be added to a rule.
    """

    TargetId: Optional[str] = None
    """
    The ID of the target.
    """
    ErrorCode: Optional[str] = None
    """
    The error code that indicates why the target addition failed.

    If the value is ``ConcurrentModificationException``, too
    many requests were made at the same time.
    """
    ErrorMessage: Optional[str] = None
    """
    The error message that explains why the target addition failed.
    """


class PutTargetsResponse(Boto3Model):
    FailedEntryCount: Optional[int] = None
    """
    The number of failed entries.
    """
    FailedEntries: Optional[List["PutTargetsResultEntry"]] = None
    """
    The failed target entries.
    """


class RemoveTargetsResultEntry(Boto3Model):
    """
    Represents a target that failed to be removed from a rule.
    """

    TargetId: Optional[str] = None
    """
    The ID of the target.
    """
    ErrorCode: Optional[str] = None
    """
    The error code that indicates why the target removal failed.

    If the value is ``ConcurrentModificationException``, too
    many requests were made at the same time.
    """
    ErrorMessage: Optional[str] = None
    """
    The error message that explains why the target removal failed.
    """


class RemoveTargetsResponse(Boto3Model):
    FailedEntryCount: Optional[int] = None
    """
    The number of failed entries.
    """
    FailedEntries: Optional[List["RemoveTargetsResultEntry"]] = None
    """
    The failed target entries.
    """
