# 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 CloudWatchAlarmProperties(TypedDict):
    ComparisonOperator: str | None
    EvaluationPeriods: int | None
    ActionsEnabled: bool | None
    AlarmActions: list[str] | None
    AlarmDescription: str | None
    AlarmName: str | None
    Arn: str | None
    DatapointsToAlarm: int | None
    Dimensions: list[Dimension] | None
    EvaluateLowSampleCountPercentile: str | None
    ExtendedStatistic: str | None
    Id: str | None
    InsufficientDataActions: list[str] | None
    MetricName: str | None
    Metrics: list[MetricDataQuery] | None
    Namespace: str | None
    OKActions: list[str] | None
    Period: int | None
    Statistic: str | None
    Threshold: float | None
    ThresholdMetricId: str | None
    TreatMissingData: str | None
    Unit: str | None


class Dimension(TypedDict):
    Name: str | None
    Value: str | None


class Metric(TypedDict):
    Dimensions: list[Dimension] | None
    MetricName: str | None
    Namespace: str | None


class MetricStat(TypedDict):
    Metric: Metric | None
    Period: int | None
    Stat: str | None
    Unit: str | None


class MetricDataQuery(TypedDict):
    Id: str | None
    AccountId: str | None
    Expression: str | None
    Label: str | None
    MetricStat: MetricStat | None
    Period: int | None
    ReturnData: bool | None


REPEATED_INVOCATION = "repeated_invocation"


class CloudWatchAlarmProvider(ResourceProvider[CloudWatchAlarmProperties]):
    TYPE = "AWS::CloudWatch::Alarm"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

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

        Primary identifier fields:
          - /properties/Id

        Required properties:
          - ComparisonOperator
          - EvaluationPeriods

        Create-only properties:
          - /properties/AlarmName

        Read-only properties:
          - /properties/Id
          - /properties/Arn



        """
        model = request.desired_state
        cloudwatch = request.aws_client_factory.cloudwatch

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

        create_params = util.select_attributes(
            model,
            [
                "AlarmName",
                "ComparisonOperator",
                "EvaluationPeriods",
                "Period",
                "MetricName",
                "Namespace",
                "Statistic",
                "Threshold",
                "ActionsEnabled",
                "AlarmActions",
                "AlarmDescription",
                "DatapointsToAlarm",
                "Dimensions",
                "EvaluateLowSampleCountPercentile",
                "ExtendedStatistic",
                "InsufficientDataActions",
                "Metrics",
                "OKActions",
                "ThresholdMetricId",
                "TreatMissingData",
                "Unit",
            ],
        )

        cloudwatch.put_metric_alarm(**create_params)
        alarms = cloudwatch.describe_alarms(AlarmNames=[model["AlarmName"]])["MetricAlarms"]
        if not alarms:
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resource_model=model,
                message="Alarm not found",
            )

        alarm = alarms[0]
        model["Arn"] = alarm["AlarmArn"]
        model["Id"] = alarm["AlarmName"]

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

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


        """
        raise NotImplementedError

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


        """
        model = request.desired_state
        cloud_watch = request.aws_client_factory.cloudwatch
        cloud_watch.delete_alarms(AlarmNames=[model["AlarmName"]])

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

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


        """
        raise NotImplementedError
