AWSTemplateFormatVersion: '2010-09-09'
Description: >
  EFS Lifecycle Policy Review Remediator.
  Purpose-specific, opt-in remediation module for reviewing Amazon EFS file systems
  and optionally applying a conservative baseline lifecycle policy to file systems
  without an existing lifecycle configuration.

Parameters:
  ProjectName:
    Type: String
    Default: efs-lifecycle-review
    Description: Short base name used for created resources.

  TargetRegionsCsv:
    Type: String
    Default: all-enabled
    Description: Comma-separated AWS Regions to scan, or all-enabled to scan all enabled Regions.

  ExcludedRegionsCsv:
    Type: String
    Default: ap-northeast-3
    Description: Comma-separated AWS Regions to exclude from scanning/remediation.

  DryRun:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only report what would happen. When false, apply eligible lifecycle policies.

  ActionMode:
    Type: String
    Default: review-only
    AllowedValues:
      - review-only
      - apply-baseline-lifecycle
    Description: review-only never changes resources. apply-baseline-lifecycle applies policy to eligible EFS file systems.

  RequireApprovalTag:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Lifecycle changes require ApprovalTagKey=ApprovalTagValue when true.

  ApprovalTagKey:
    Type: String
    Default: CostOptApproved
    Description: Tag key required when RequireApprovalTag is true.

  ApprovalTagValue:
    Type: String
    Default: 'true'
    Description: Tag value required when RequireApprovalTag is true.

  IgnoreTagKeysCsv:
    Type: String
    Default: CostOptIgnore,DoNotModify,DoNotDelete,ComplianceHold,LegalHold
    Description: Comma-separated tag keys that prevent lifecycle policy application.

  IgnoreTagPairsCsv:
    Type: String
    Default: CostOptIgnore=true,DoNotModify=true,DoNotDelete=true,ComplianceHold=true,LegalHold=true
    Description: Comma-separated key=value tag pairs that prevent lifecycle policy application.

  OnlyIfNoLifecyclePolicy:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only file systems without lifecycle policies are eligible.

  AllowOverwriteExistingLifecyclePolicy:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Allows replacing existing lifecycle policies. Not recommended for normal use.

  IncludeFileSystemNamePrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated EFS Name tag prefixes to include. Leave blank to include all.

  ExcludeFileSystemNamePrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated EFS Name tag prefixes to exclude.

  TransitionToIADays:
    Type: String
    Default: AFTER_30_DAYS
    AllowedValues:
      - AFTER_1_DAY
      - AFTER_7_DAYS
      - AFTER_14_DAYS
      - AFTER_30_DAYS
      - AFTER_60_DAYS
      - AFTER_90_DAYS
    Description: EFS lifecycle transition to Infrequent Access.

  TransitionToArchiveDays:
    Type: String
    Default: DISABLED
    AllowedValues:
      - DISABLED
      - AFTER_1_DAY
      - AFTER_7_DAYS
      - AFTER_14_DAYS
      - AFTER_30_DAYS
      - AFTER_60_DAYS
      - AFTER_90_DAYS
      - AFTER_180_DAYS
      - AFTER_270_DAYS
      - AFTER_365_DAYS
    Description: Optional EFS lifecycle transition to Archive where supported. DISABLED omits this rule.

  TransitionToPrimaryStorageClass:
    Type: String
    Default: DISABLED
    AllowedValues:
      - DISABLED
      - AFTER_1_ACCESS
    Description: Optional return-to-primary-storage policy. DISABLED omits this rule.

  MinimumSizeGiB:
    Type: Number
    Default: 0
    Description: Optional size filter. 0 means all file systems are reviewed.

  MaxFileSystemsPerRun:
    Type: Number
    Default: 50
    Description: Safety limit. 0 means no limit. Recommended actual apply batch is 5 to 25.

  ContinueOnAccessDenied:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Continue scanning other Regions/file systems when blocked by IAM/SCP.

  ScheduleEnabled:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Whether to create an enabled EventBridge schedule.

  ScheduleExpression:
    Type: String
    Default: rate(30 days)
    Description: EventBridge schedule expression used when ScheduleEnabled is true.

Conditions:
  IsScheduleEnabled: !Equals [!Ref ScheduleEnabled, 'true']

Resources:
  RemediatorRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: EfsLifecycleReviewPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: DiscoverRegions
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                Resource: '*'
              - Sid: ReadEfs
                Effect: Allow
                Action:
                  - elasticfilesystem:DescribeFileSystems
                  - elasticfilesystem:DescribeLifecycleConfiguration
                  - elasticfilesystem:DescribeTags
                  - elasticfilesystem:ListTagsForResource
                Resource: '*'
              - Sid: PutEfsLifecycleConfiguration
                Effect: Allow
                Action:
                  - elasticfilesystem:PutLifecycleConfiguration
                Resource: '*'

  RemediatorFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ProjectName
      Description: Purpose-specific Lambda for EFS lifecycle policy review and guarded baseline application.
      Runtime: python3.12
      Handler: index.handler
      Timeout: 900
      MemorySize: 512
      Role: !GetAtt RemediatorRole.Arn
      Environment:
        Variables:
          TARGET_REGIONS_CSV: !Ref TargetRegionsCsv
          EXCLUDED_REGIONS_CSV: !Ref ExcludedRegionsCsv
          DRY_RUN: !Ref DryRun
          ACTION_MODE: !Ref ActionMode
          REQUIRE_APPROVAL_TAG: !Ref RequireApprovalTag
          APPROVAL_TAG_KEY: !Ref ApprovalTagKey
          APPROVAL_TAG_VALUE: !Ref ApprovalTagValue
          IGNORE_TAG_KEYS_CSV: !Ref IgnoreTagKeysCsv
          IGNORE_TAG_PAIRS_CSV: !Ref IgnoreTagPairsCsv
          ONLY_IF_NO_LIFECYCLE_POLICY: !Ref OnlyIfNoLifecyclePolicy
          ALLOW_OVERWRITE_EXISTING_LIFECYCLE_POLICY: !Ref AllowOverwriteExistingLifecyclePolicy
          INCLUDE_FILE_SYSTEM_NAME_PREFIXES_CSV: !Ref IncludeFileSystemNamePrefixesCsv
          EXCLUDE_FILE_SYSTEM_NAME_PREFIXES_CSV: !Ref ExcludeFileSystemNamePrefixesCsv
          TRANSITION_TO_IA_DAYS: !Ref TransitionToIADays
          TRANSITION_TO_ARCHIVE_DAYS: !Ref TransitionToArchiveDays
          TRANSITION_TO_PRIMARY_STORAGE_CLASS: !Ref TransitionToPrimaryStorageClass
          MINIMUM_SIZE_GIB: !Ref MinimumSizeGiB
          MAX_FILE_SYSTEMS_PER_RUN: !Ref MaxFileSystemsPerRun
          CONTINUE_ON_ACCESS_DENIED: !Ref ContinueOnAccessDenied
      Code:
        ZipFile: |
          import json
          import os
          import traceback
          from datetime import datetime, timezone

          import boto3
          from botocore.exceptions import ClientError

          GIB = 1024 ** 3

          def utc_now_iso():
              return datetime.now(timezone.utc).isoformat()

          def env_bool(name, default=False):
              return os.environ.get(name, str(default)).strip().lower() in ('1', 'true', 'yes', 'y')

          def env_int(name, default=0):
              try:
                  return int(os.environ.get(name, str(default)).strip())
              except Exception:
                  return default

          def split_csv(value):
              if value is None:
                  return []
              return [x.strip() for x in str(value).split(',') if x.strip()]

          def parse_tag_pairs(value):
              pairs = {}
              for item in split_csv(value):
                  if '=' not in item:
                      continue
                  key, val = item.split('=', 1)
                  if key.strip():
                      pairs[key.strip()] = val.strip()
              return pairs

          def get_enabled_regions(excluded_regions):
              requested = os.environ.get('TARGET_REGIONS_CSV', 'all-enabled').strip()
              if requested and requested.lower() != 'all-enabled':
                  regions = split_csv(requested)
              else:
                  ec2 = boto3.client('ec2', region_name=os.environ.get('AWS_REGION', 'us-east-1'))
                  response = ec2.describe_regions(AllRegions=False)
                  regions = sorted([r['RegionName'] for r in response.get('Regions', [])])
              return [r for r in regions if r not in excluded_regions]

          def bytes_to_gib(value):
              try:
                  return round(float(value or 0) / GIB, 3)
              except Exception:
                  return 0.0

          def name_from_tags(tags):
              return tags.get('Name', '')

          def name_included(name, include_prefixes):
              if not include_prefixes:
                  return True
              return any((name or '').startswith(prefix) for prefix in include_prefixes)

          def name_excluded(name, exclude_prefixes):
              if not exclude_prefixes:
                  return False
              return any((name or '').startswith(prefix) for prefix in exclude_prefixes)

          def has_ignore_tag(tags, ignore_keys, ignore_pairs):
              for key in ignore_keys:
                  if key in tags:
                      return True, 'ignore_tag_key=' + key
              for key, value in ignore_pairs.items():
                  if tags.get(key) == value:
                      return True, 'ignore_tag_pair=' + key + '=' + value
              return False, ''

          def has_approval_tag(tags, settings):
              if not settings['require_approval_tag']:
                  return True
              return tags.get(settings['approval_tag_key']) == settings['approval_tag_value']

          def tags_to_dict(tag_list):
              return {t.get('Key'): t.get('Value', '') for t in tag_list or [] if t.get('Key')}

          def list_tags(efs, fs_id):
              try:
                  response = efs.list_tags_for_resource(ResourceId=fs_id)
                  return tags_to_dict(response.get('Tags', []))
              except ClientError:
                  try:
                      response = efs.describe_tags(FileSystemId=fs_id)
                      return tags_to_dict(response.get('Tags', []))
                  except ClientError:
                      return {}

          def describe_file_systems(efs):
              items = []
              paginator = efs.get_paginator('describe_file_systems')
              for page in paginator.paginate():
                  items.extend(page.get('FileSystems', []))
              return items

          def get_lifecycle(efs, fs_id):
              try:
                  response = efs.describe_lifecycle_configuration(FileSystemId=fs_id)
                  policies = response.get('LifecyclePolicies', [])
                  return policies, None
              except ClientError as e:
                  return [], e

          def build_lifecycle_policy(settings):
              policies = []
              ia = settings['transition_to_ia_days']
              archive = settings['transition_to_archive_days']
              primary = settings['transition_to_primary_storage_class']

              if ia and ia != 'DISABLED':
                  policies.append({'TransitionToIA': ia})
              if archive and archive != 'DISABLED':
                  policies.append({'TransitionToArchive': archive})
              if primary and primary != 'DISABLED':
                  policies.append({'TransitionToPrimaryStorageClass': primary})

              return policies

          def scan_region(region, settings):
              efs = boto3.client('efs', region_name=region)
              result = {
                  'region': region,
                  'evaluated_file_systems': 0,
                  'file_systems': 0,
                  'file_systems_without_lifecycle_policy': 0,
                  'file_systems_with_lifecycle_policy': 0,
                  'eligible': 0,
                  'would_apply': 0,
                  'applied': 0,
                  'total_size_gib': 0.0,
                  'eligible_size_gib': 0.0,
                  'skipped_existing_lifecycle_policy': 0,
                  'skipped_no_baseline_policy_rules': 0,
                  'skipped_too_small': 0,
                  'skipped_include_prefix': 0,
                  'skipped_exclude_prefix': 0,
                  'skipped_missing_approval_tag': 0,
                  'skipped_ignore_tag': 0,
                  'access_denied': 0,
                  'failed': 0,
                  'failures': [],
                  'candidates': [],
                  'applied_file_systems': []
              }

              try:
                  file_systems = describe_file_systems(efs)
              except ClientError as e:
                  code = e.response.get('Error', {}).get('Code', 'Unknown')
                  message = e.response.get('Error', {}).get('Message', str(e))
                  result['failures'].append({'operation': 'DescribeFileSystems', 'error_code': code, 'error_message': message})
                  if code in ('AccessDenied', 'AccessDeniedException') or 'explicit deny' in message.lower():
                      result['access_denied'] += 1
                  else:
                      result['failed'] += 1
                  if not settings['continue_on_access_denied']:
                      raise
                  return result

              baseline_policy = build_lifecycle_policy(settings)
              if not baseline_policy:
                  result['skipped_no_baseline_policy_rules'] = len(file_systems)
                  return result

              for fs in file_systems:
                  if settings['max_file_systems_per_run'] and (result['would_apply'] + result['applied']) >= settings['max_file_systems_per_run']:
                      result['stopped_due_to_max_file_systems_per_run'] = True
                      return result

                  fs_id = fs.get('FileSystemId')
                  arn = fs.get('FileSystemArn')
                  result['evaluated_file_systems'] += 1
                  result['file_systems'] += 1

                  tags = list_tags(efs, fs_id)
                  name = name_from_tags(tags)
                  size_gib = bytes_to_gib((fs.get('SizeInBytes') or {}).get('Value'))
                  result['total_size_gib'] += size_gib

                  item = {
                      'file_system_id': fs_id,
                      'file_system_arn': arn,
                      'name': name,
                      'region': region,
                      'creation_time': str(fs.get('CreationTime')),
                      'life_cycle_state': fs.get('LifeCycleState'),
                      'performance_mode': fs.get('PerformanceMode'),
                      'throughput_mode': fs.get('ThroughputMode'),
                      'encrypted': fs.get('Encrypted'),
                      'size_gib': size_gib,
                      'number_of_mount_targets': fs.get('NumberOfMountTargets'),
                      'tags': tags
                  }

                  if not name_included(name, settings['include_name_prefixes']):
                      result['skipped_include_prefix'] += 1
                      continue

                  if name_excluded(name, settings['exclude_name_prefixes']):
                      result['skipped_exclude_prefix'] += 1
                      item['action'] = 'skipped_exclude_prefix'
                      result['candidates'].append(item)
                      continue

                  if settings['minimum_size_gib'] and size_gib < settings['minimum_size_gib']:
                      result['skipped_too_small'] += 1
                      item['action'] = 'skipped_too_small'
                      result['candidates'].append(item)
                      continue

                  ignore, reason = has_ignore_tag(tags, settings['ignore_tag_keys'], settings['ignore_tag_pairs'])
                  if ignore:
                      result['skipped_ignore_tag'] += 1
                      item['action'] = 'skipped_ignore_tag'
                      item['reason'] = reason
                      result['candidates'].append(item)
                      continue

                  lifecycle, lifecycle_error = get_lifecycle(efs, fs_id)
                  if lifecycle_error:
                      code = lifecycle_error.response.get('Error', {}).get('Code', 'Unknown')
                      message = lifecycle_error.response.get('Error', {}).get('Message', str(lifecycle_error))
                      result['failures'].append({'file_system_id': fs_id, 'operation': 'DescribeLifecycleConfiguration', 'error_code': code, 'error_message': message})
                      if code in ('AccessDenied', 'AccessDeniedException') or 'explicit deny' in message.lower():
                          result['access_denied'] += 1
                      else:
                          result['failed'] += 1
                      if not settings['continue_on_access_denied']:
                          raise lifecycle_error
                      continue

                  item['existing_lifecycle_policy'] = lifecycle
                  has_lifecycle = len(lifecycle) > 0

                  if has_lifecycle:
                      result['file_systems_with_lifecycle_policy'] += 1
                      if settings['only_if_no_lifecycle_policy'] and not settings['allow_overwrite_existing_lifecycle_policy']:
                          result['skipped_existing_lifecycle_policy'] += 1
                          item['action'] = 'skipped_existing_lifecycle_policy'
                          result['candidates'].append(item)
                          continue
                  else:
                      result['file_systems_without_lifecycle_policy'] += 1

                  if not has_approval_tag(tags, settings):
                      result['skipped_missing_approval_tag'] += 1
                      item['action'] = 'skipped_missing_approval_tag'
                      item['required_tag'] = settings['approval_tag_key'] + '=' + settings['approval_tag_value']
                      result['candidates'].append(item)
                      continue

                  result['eligible'] += 1
                  result['eligible_size_gib'] += size_gib
                  item['new_lifecycle_policy'] = baseline_policy

                  if settings['action_mode'] != 'apply-baseline-lifecycle':
                      item['action'] = 'review_only_candidate'
                      result['candidates'].append(item)
                      continue

                  item['action'] = 'would_apply' if settings['dry_run'] else 'apply'

                  if settings['dry_run']:
                      result['would_apply'] += 1
                      result['candidates'].append(item)
                      continue

                  try:
                      efs.put_lifecycle_configuration(
                          FileSystemId=fs_id,
                          LifecyclePolicies=baseline_policy
                      )
                      result['applied'] += 1
                      result['applied_file_systems'].append(item)
                  except ClientError as e:
                      code = e.response.get('Error', {}).get('Code', 'Unknown')
                      message = e.response.get('Error', {}).get('Message', str(e))
                      result['failures'].append({'file_system_id': fs_id, 'operation': 'PutLifecycleConfiguration', 'error_code': code, 'error_message': message})
                      if code in ('AccessDenied', 'AccessDeniedException') or 'explicit deny' in message.lower():
                          result['access_denied'] += 1
                      else:
                          result['failed'] += 1
                      if not settings['continue_on_access_denied']:
                          raise

              result['total_size_gib'] = round(result['total_size_gib'], 3)
              result['eligible_size_gib'] = round(result['eligible_size_gib'], 3)
              return result

          def handler(event, context):
              settings = {
                  'excluded_regions': split_csv(os.environ.get('EXCLUDED_REGIONS_CSV', '')),
                  'dry_run': env_bool('DRY_RUN', True),
                  'action_mode': os.environ.get('ACTION_MODE', 'review-only'),
                  'require_approval_tag': env_bool('REQUIRE_APPROVAL_TAG', True),
                  'approval_tag_key': os.environ.get('APPROVAL_TAG_KEY', 'CostOptApproved'),
                  'approval_tag_value': os.environ.get('APPROVAL_TAG_VALUE', 'true'),
                  'ignore_tag_keys': split_csv(os.environ.get('IGNORE_TAG_KEYS_CSV', '')),
                  'ignore_tag_pairs': parse_tag_pairs(os.environ.get('IGNORE_TAG_PAIRS_CSV', '')),
                  'only_if_no_lifecycle_policy': env_bool('ONLY_IF_NO_LIFECYCLE_POLICY', True),
                  'allow_overwrite_existing_lifecycle_policy': env_bool('ALLOW_OVERWRITE_EXISTING_LIFECYCLE_POLICY', False),
                  'include_name_prefixes': split_csv(os.environ.get('INCLUDE_FILE_SYSTEM_NAME_PREFIXES_CSV', '')),
                  'exclude_name_prefixes': split_csv(os.environ.get('EXCLUDE_FILE_SYSTEM_NAME_PREFIXES_CSV', '')),
                  'transition_to_ia_days': os.environ.get('TRANSITION_TO_IA_DAYS', 'AFTER_30_DAYS'),
                  'transition_to_archive_days': os.environ.get('TRANSITION_TO_ARCHIVE_DAYS', 'DISABLED'),
                  'transition_to_primary_storage_class': os.environ.get('TRANSITION_TO_PRIMARY_STORAGE_CLASS', 'DISABLED'),
                  'minimum_size_gib': env_int('MINIMUM_SIZE_GIB', 0),
                  'max_file_systems_per_run': env_int('MAX_FILE_SYSTEMS_PER_RUN', 50),
                  'continue_on_access_denied': env_bool('CONTINUE_ON_ACCESS_DENIED', True),
              }

              if isinstance(event, dict):
                  if 'dry_run' in event:
                      settings['dry_run'] = bool(event['dry_run'])
                  if 'action_mode' in event:
                      settings['action_mode'] = str(event['action_mode'])
                  if 'require_approval_tag' in event:
                      settings['require_approval_tag'] = bool(event['require_approval_tag'])
                  if 'transition_to_ia_days' in event:
                      settings['transition_to_ia_days'] = str(event['transition_to_ia_days'])
                  if 'transition_to_archive_days' in event:
                      settings['transition_to_archive_days'] = str(event['transition_to_archive_days'])
                  if 'transition_to_primary_storage_class' in event:
                      settings['transition_to_primary_storage_class'] = str(event['transition_to_primary_storage_class'])
                  if 'minimum_size_gib' in event:
                      settings['minimum_size_gib'] = int(event['minimum_size_gib'])
                  if 'max_file_systems_per_run' in event:
                      settings['max_file_systems_per_run'] = int(event['max_file_systems_per_run'])
                  if 'target_regions' in event and event['target_regions']:
                      os.environ['TARGET_REGIONS_CSV'] = ','.join(event['target_regions'])
                  if 'excluded_regions' in event and event['excluded_regions']:
                      settings['excluded_regions'] = list(event['excluded_regions'])

              if settings['action_mode'] not in ('review-only', 'apply-baseline-lifecycle'):
                  settings['action_mode'] = 'review-only'

              summary = {
                  'started_at': utc_now_iso(),
                  'dry_run': settings['dry_run'],
                  'action_mode': settings['action_mode'],
                  'require_approval_tag': settings['require_approval_tag'],
                  'approval_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                  'only_if_no_lifecycle_policy': settings['only_if_no_lifecycle_policy'],
                  'allow_overwrite_existing_lifecycle_policy': settings['allow_overwrite_existing_lifecycle_policy'],
                  'baseline_lifecycle_policy': build_lifecycle_policy(settings),
                  'minimum_size_gib': settings['minimum_size_gib'],
                  'max_file_systems_per_run': settings['max_file_systems_per_run'],
                  'excluded_regions': settings['excluded_regions'],
                  'regions': [],
                  'totals': {
                      'evaluated_file_systems': 0,
                      'file_systems': 0,
                      'file_systems_without_lifecycle_policy': 0,
                      'file_systems_with_lifecycle_policy': 0,
                      'eligible': 0,
                      'would_apply': 0,
                      'applied': 0,
                      'total_size_gib': 0,
                      'eligible_size_gib': 0,
                      'skipped_existing_lifecycle_policy': 0,
                      'skipped_no_baseline_policy_rules': 0,
                      'skipped_too_small': 0,
                      'skipped_include_prefix': 0,
                      'skipped_exclude_prefix': 0,
                      'skipped_missing_approval_tag': 0,
                      'skipped_ignore_tag': 0,
                      'access_denied': 0,
                      'failed': 0
                  },
                  'region_results': []
              }

              try:
                  regions = get_enabled_regions(settings['excluded_regions'])
                  summary['regions'] = regions
                  for region in regions:
                      try:
                          rr = scan_region(region, settings)
                      except Exception as e:
                          rr = {
                              'region': region,
                              'evaluated_file_systems': 0,
                              'file_systems': 0,
                              'file_systems_without_lifecycle_policy': 0,
                              'file_systems_with_lifecycle_policy': 0,
                              'eligible': 0,
                              'would_apply': 0,
                              'applied': 0,
                              'total_size_gib': 0,
                              'eligible_size_gib': 0,
                              'skipped_existing_lifecycle_policy': 0,
                              'skipped_no_baseline_policy_rules': 0,
                              'skipped_too_small': 0,
                              'skipped_include_prefix': 0,
                              'skipped_exclude_prefix': 0,
                              'skipped_missing_approval_tag': 0,
                              'skipped_ignore_tag': 0,
                              'access_denied': 0,
                              'failed': 1,
                              'failures': [{'error_code': type(e).__name__, 'error_message': str(e), 'trace': traceback.format_exc()}],
                              'candidates': [],
                              'applied_file_systems': []
                          }
                      summary['region_results'].append(rr)
                      for key in summary['totals']:
                          summary['totals'][key] += rr.get(key, 0) or 0
                  summary['totals']['total_size_gib'] = round(summary['totals']['total_size_gib'], 3)
                  summary['totals']['eligible_size_gib'] = round(summary['totals']['eligible_size_gib'], 3)
              finally:
                  summary['ended_at'] = utc_now_iso()
                  print(json.dumps(summary, indent=2, default=str))
              return summary

  RemediatorScheduleRule:
    Type: AWS::Events::Rule
    Condition: IsScheduleEnabled
    Properties:
      Name: !Sub '${ProjectName}-schedule'
      Description: Scheduled run for EFS Lifecycle Policy Review Remediator.
      ScheduleExpression: !Ref ScheduleExpression
      State: ENABLED
      Targets:
        - Arn: !GetAtt RemediatorFunction.Arn
          Id: EfsLifecycleReviewTarget
          Input: '{"source":"eventbridge-schedule","dry_run":true,"action_mode":"review-only"}'

  RemediatorSchedulePermission:
    Type: AWS::Lambda::Permission
    Condition: IsScheduleEnabled
    Properties:
      FunctionName: !Ref RemediatorFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt RemediatorScheduleRule.Arn

Outputs:
  RemediatorFunctionName:
    Description: Lambda function name.
    Value: !Ref RemediatorFunction

  RemediatorFunctionArn:
    Description: Lambda function ARN.
    Value: !GetAtt RemediatorFunction.Arn

  DryRunSetting:
    Description: Current DryRun setting.
    Value: !Ref DryRun

  ActionModeSetting:
    Description: Current ActionMode setting.
    Value: !Ref ActionMode

  ManualReviewExample:
    Description: Example manual review invocation payload.
    Value: !Sub 'aws lambda invoke --function-name ${RemediatorFunction} --cli-binary-format raw-in-base64-out --payload ''{"dry_run":true,"action_mode":"review-only","require_approval_tag":false}'' response.json'
