AWSTemplateFormatVersion: '2010-09-09'
Description: '>> DEPLOY IN US-EAST-1 ONLY << CloudWise Cost Monitoring Setup (CUR 1.0 + CUR 2.0) - This template MUST be deployed in us-east-1 (N. Virginia) because AWS Cost Report APIs are only available there.'

Metadata:
  # CloudWise Template Version - Used for update notifications
  # Increment this when adding new permissions or features that require user stack updates
  CloudWise:
    TemplateVersion: "1.20.0"
    LastUpdated: "2026-04-16"
    ChangeLog:
      - Version: "1.20.0"
        Date: "2026-04-16"
        Changes:
          - "Added elasticache:ListTagsForResource for ElastiCache environment tag detection (replication waste, non-production replica identification)"
      - Version: "1.19.0"
        Date: "2026-04-15"
        Changes:
          - "Added elasticbeanstalk:DescribeConfigurationSettings for Beanstalk environment configuration analysis (unnecessary ALB, previous-gen instances, over-provisioned detection)"
          - "Added elasticbeanstalk:DescribeInstancesHealth for Beanstalk instance-level health metrics"
      - Version: "1.18.0"
        Date: "2026-04-12"
        Changes:
          - "Added workspaces:DescribeWorkspaceBundles for WorkSpaces bundle rightsizing detection"
          - "Added workspaces:DescribeWorkspacesPools for WorkSpaces pool overprovisioning detection"
      - Version: "1.17.0"
        Date: "2026-04-14"
        Changes:
          - "Added elasticmapreduce:ListSteps for EMR step history analysis (long-running cluster detection)"
          - "Added elasticmapreduce:GetAutoTerminationPolicy for EMR auto-termination waste detection"
          - "Added elasticmapreduce:DescribeStep for EMR step detail inspection"
      - Version: "1.16.0"
        Date: "2026-04-13"
        Changes:
          - "Added kinesis:ListStreamConsumers, kinesis:DescribeStreamConsumer for Kinesis enhanced fan-out waste detection"
          - "Added firehose:ListDeliveryStreams, firehose:DescribeDeliveryStream for Firehose idle delivery stream detection"
      - Version: "1.15.0"
        Date: "2026-04-08"
        Changes:
          - "Added savingsplans:DescribeSavingsPlans for commitment risk intelligence (RI/Savings Plan analysis)"
      - Version: "1.14.0"
        Date: "2026-04-05"
        Changes:
          - "Added iam:SimulatePrincipalPolicy for comprehensive dry-run permission verification (Troubleshoot Connection)"
      - Version: "1.13.0"
        Date: "2026-04-04"
        Changes:
          - "Added lightsail:GetStaticIps, GetDisks, GetInstanceSnapshots, GetLoadBalancers, GetRelationalDatabases for Lightsail waste detection expansion"
      - Version: "1.12.0"
        Date: "2026-04-01"
        Changes:
          - "Added eks:ListClusters and eks:DescribeCluster for EKS extended-support waste detection"
      - Version: "1.11.0"
        Date: "2026-03-27"
        Changes:
          - "Added mq:DescribeBroker for MQ broker waste detection (idle and oversized)"
      - Version: "1.10.0"
        Date: "2026-03-24"
        Changes:
          - "Added appsync:GetApiCache for AppSync idle cache waste detection"
      - Version: "1.9.0"
        Date: "2026-03-19"
        Changes:
          - "Added es:DescribeDomains for OpenSearch expanded waste detection (oversized domain, EBS overprovisioned, RI opportunity)"
      - Version: "1.8.0"
        Date: "2026-03-18"
        Changes:
          - "Added fsx:DescribeBackups for FSx old backup waste detection"
      - Version: "1.7.0"
        Date: "2026-03-18"
        Changes:
          - "Added rds:DescribeDBClusterSnapshots for DocumentDB old snapshot detection"
          - "Added rds:ListTagsForResource for DocumentDB snapshot retention tag checking"
      - Version: "1.6.0"
        Date: "2026-03-17"
        Changes:
          - "Added AWS Backup read permissions for backup waste detection (5 new detectors)"
          - "backup:ListBackupVaults, ListRecoveryPointsByBackupVault, ListBackupPlans, GetBackupPlan, ListBackupSelections, GetBackupSelection, ListCopyJobs"
      - Version: "1.5.0"
        Date: "2026-03-12"
        Changes:
          - "Added ecs:ListTaskDefinitions, ecs:ListTagsForResource permissions for ECS/Fargate waste detection"
      - Version: "1.4.0"
        Date: "2026-02-28"
        Changes:
          - "Added CUR 2.0 (Data Exports) support - users can choose between CUR 1.0 and CUR 2.0 format"
          - "Added bcm-data-exports:GetExport, bcm-data-exports:ListExports IAM permissions"
          - "Added AWS::BCMDataExports::Export resource for CUR 2.0 deployments"
          - "S3 bucket policy now includes both billingreports and bcm-data-exports service principals"
      - Version: "1.3.0"
        Date: "2026-02-23"
        Changes:
          - "Added sagemaker:DescribeNotebookInstance, sagemaker:DescribeEndpoint, sagemaker:DescribeEndpointConfig permissions for SageMaker waste detection"
      - Version: "1.2.0"
        Date: "2026-01-25"
        Changes:
          - "Added lambda:ListProvisionedConcurrencyConfigs permission for Lambda waste detection"
          - "Fixed permission gap that caused AccessDenied errors during Lambda analysis"
      - Version: "1.1.0"
        Date: "2026-01-19"
        Changes:
          - "Added region validation rule - template now fails gracefully with clear error if not deployed in us-east-1"
          - "Updated description to prominently warn about us-east-1 requirement"
      - Version: "1.0.0"
        Date: "2026-01-02"
        Changes:
          - "Initial versioned template"
          - "90+ Waste Detectors including EC2, EBS, RDS, Lambda, S3, DynamoDB"
          - "Compute Optimizer integration for ML-backed recommendations"
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "Cost Report Format"
        Parameters:
          - CURVersion
      - Label:
          default: "Security Settings (Pre-configured - Do Not Change)"
        Parameters:
          - CloudWiseAccountId
          - ExternalId
    ParameterLabels:
      CURVersion:
        default: "AWS Cost Report Version (CUR 1.0 or CUR 2.0)"
      CloudWiseAccountId:
        default: "CloudWise Service Account (Read-Only)"
      ExternalId:
        default: "Security Key (Read-Only)"

Parameters:
  CloudWiseAccountId:
    Type: String
    Description: "CloudWise service account ID (DO NOT CHANGE - required for CloudWise to access your cost data)"
    Default: "513158236564"
    AllowedValues:
      - "513158236564"
    ConstraintDescription: This value cannot be changed

  ExternalId:
    Type: String
    Description: "Security key for CloudWise access (DO NOT CHANGE - pre-configured for security)"
    Default: "cloudwise-cost-access-2025"
    AllowedValues:
      - "cloudwise-cost-access-2025"
    NoEcho: true

  CURVersion:
    Type: String
    Description: "Choose your AWS Cost Report format. CUR 1.0 (Legacy) is the standard Cost and Usage Report. CUR 2.0 (Data Exports) uses the newer AWS Billing and Cost Management Data Exports service with improved column naming. CloudWise supports both formats."
    Default: "1.0"
    AllowedValues:
      - "1.0"
      - "2.0"

Conditions:
  IsCUR1: !Equals [!Ref CURVersion, "1.0"]
  IsCUR2: !Equals [!Ref CURVersion, "2.0"]

# NOTE: CloudFormation Rules cannot prevent the "Unrecognized resource types" error
# because AWS rejects AWS::CUR::ReportDefinition during template parsing (before rules run).
# The us-east-1 requirement is enforced by:
# 1. The CloudWise UI which opens AWS Console directly in us-east-1
# 2. Clear documentation and warnings in the UI
# See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cur-reportdefinition.html

Resources:
  # S3 Bucket for Cost Reports
  # Note: Bucket can be in any region, but CUR service is only in us-east-1
  CostReportsBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub 'cloudwise-cur-${AWS::AccountId}-${AWS::Region}'
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled
      LifecycleConfiguration:
        Rules:
          - Id: DeleteOldReports
            Status: Enabled
            ExpirationInDays: 90  # Keep reports for 90 days
            AbortIncompleteMultipartUpload:
              DaysAfterInitiation: 1
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  # Bucket Policy to Allow AWS Billing Service
  CostReportsBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref CostReportsBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: AllowAWSBillingReports
            Effect: Allow
            Principal:
              Service: billingreports.amazonaws.com
            Action:
              - s3:GetBucketAcl
              - s3:GetBucketPolicy
            Resource: !GetAtt CostReportsBucket.Arn
            Condition:
              StringEquals:
                'aws:SourceArn': !Sub 'arn:aws:cur:us-east-1:${AWS::AccountId}:definition/*'
                'aws:SourceAccount': !Ref AWS::AccountId
          - Sid: AllowAWSBillingDelivery
            Effect: Allow
            Principal:
              Service: billingreports.amazonaws.com
            Action:
              - s3:PutObject
            Resource: !Sub '${CostReportsBucket.Arn}/*'
            Condition:
              StringEquals:
                'aws:SourceArn': !Sub 'arn:aws:cur:us-east-1:${AWS::AccountId}:definition/*'
                'aws:SourceAccount': !Ref AWS::AccountId
          # CUR 2.0 (Data Exports) service access - included regardless of CUR
          # version to allow seamless upgrades from CUR 1.0 to 2.0
          # NOTE: Unlike CUR 1.0, the Data Exports service validates bucket permissions
          # during export creation (before the export ARN exists). Using SourceArn here
          # causes a chicken-and-egg failure. SourceAccount is sufficient security.
          - Sid: AllowDataExportsReports
            Effect: Allow
            Principal:
              Service: bcm-data-exports.amazonaws.com
            Action:
              - s3:GetBucketAcl
              - s3:GetBucketPolicy
            Resource: !GetAtt CostReportsBucket.Arn
            Condition:
              StringEquals:
                'aws:SourceAccount': !Ref AWS::AccountId
          - Sid: AllowDataExportsDelivery
            Effect: Allow
            Principal:
              Service: bcm-data-exports.amazonaws.com
            Action:
              - s3:PutObject
            Resource: !Sub '${CostReportsBucket.Arn}/*'
            Condition:
              StringEquals:
                'aws:SourceAccount': !Ref AWS::AccountId

  # Cost and Usage Report Definition (CUR 1.0 - Legacy format)
  # CUR reports are always generated in us-east-1 regardless of stack deployment region
  CostUsageReport:
    Type: AWS::CUR::ReportDefinition
    Condition: IsCUR1
    DependsOn: 
      - CostReportsBucketPolicy
    Properties:
      ReportName: !Sub 'CloudWiseReports-${AWS::AccountId}'
      TimeUnit: DAILY
      Format: textORcsv
      Compression: GZIP
      AdditionalSchemaElements:
        - RESOURCES
      S3Bucket: !Ref CostReportsBucket
      S3Prefix: 'daily-v1'
      S3Region: 'us-east-1'
      RefreshClosedReports: true
      ReportVersioning: OVERWRITE_REPORT

  # Cost and Usage Report via Data Exports (CUR 2.0 - Modern format)
  # Uses AWS Billing and Cost Management Data Exports service
  CostUsageDataExport:
    Type: AWS::BCMDataExports::Export
    Condition: IsCUR2
    DependsOn:
      - CostReportsBucketPolicy
    Properties:
      Export:
        Name: !Sub 'CloudWiseReports-${AWS::AccountId}'
        Description: 'CloudWise Cost and Usage Report (CUR 2.0 via Data Exports)'
        DataQuery:
          QueryStatement: "SELECT * FROM COST_AND_USAGE_REPORT"
          TableConfigurations:
            COST_AND_USAGE_REPORT:
              TIME_GRANULARITY: DAILY
              INCLUDE_RESOURCES: "TRUE"
              INCLUDE_MANUAL_DISCOUNT_COMPATIBILITY: "TRUE"
              INCLUDE_SPLIT_COST_ALLOCATION_DATA: "TRUE"
        DestinationConfigurations:
          S3Destination:
            S3Bucket: !Ref CostReportsBucket
            S3Prefix: 'daily-v2'
            S3Region: 'us-east-1'
            S3OutputConfigurations:
              OutputType: CUSTOM
              Format: TEXT_OR_CSV
              Compression: GZIP
              Overwrite: OVERWRITE_REPORT
        RefreshCadence:
          Frequency: SYNCHRONOUS

  # IAM Role for CloudWise Access
  CloudWiseAccessRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: 'CloudWise-Cost-Monitoring-Role'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          # Allow only CloudWise service role (three-tier security architecture)
          - Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${CloudWiseAccountId}:role/cloudwise-customer-access-service-role'
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                'sts:ExternalId': !Ref ExternalId

  # IAM Policy for S3 and Cost Access
  CloudWiseCostPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: 'CloudWise-Cost-Monitoring-Policy'
      Roles:
        - !Ref CloudWiseAccessRole
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # S3 Access for Cost Data
          - Sid: AllowCostDataAccess
            Effect: Allow
            Action:
              - s3:GetObject
              - s3:ListBucket
              - s3:GetBucketLocation
            Resource:
              - !GetAtt CostReportsBucket.Arn
              - !Sub '${CostReportsBucket.Arn}/*'
          
          # Cost Report Access (CUR 1.0 + CUR 2.0 Data Exports)
          - Sid: AllowCostReportAccess
            Effect: Allow
            Action:
              - cur:DescribeReportDefinitions
              - bcm-data-exports:GetExport
              - bcm-data-exports:ListExports
            Resource: '*'
            
          # Cost Explorer Access (for transition period and validation)
          - Sid: AllowCostExplorerAccess
            Effect: Allow
            Action:
              - ce:GetCostAndUsage
              - ce:GetDimensionValues
              - ce:GetReservationCoverage
              - ce:GetReservationPurchaseRecommendation
              - ce:GetReservationUtilization
              - ce:GetSavingsPlansUtilization
              - ce:GetSavingsPlansCoverage
              - ce:GetSavingsPlansPurchaseRecommendation
              - ce:GetCostCategories
              - ce:GetRightsizingRecommendation
              - ce:GetSavingsPlansUtilizationDetails
            Resource: '*'

          # Savings Plans read-only access (commitment risk analysis)
          - Sid: AllowSavingsPlansAccess
            Effect: Allow
            Action:
              - savingsplans:DescribeSavingsPlans
            Resource: '*'

          # Compute Optimizer Access (ML-backed rightsizing recommendations)
          - Sid: AllowComputeOptimizerAccess
            Effect: Allow
            Action:
              - compute-optimizer:GetEnrollmentStatus
              - compute-optimizer:GetEC2InstanceRecommendations
              - compute-optimizer:GetEBSVolumeRecommendations
              - compute-optimizer:GetLambdaFunctionRecommendations
              - compute-optimizer:GetAutoScalingGroupRecommendations
            Resource: '*'

          # Organizations Access (if using consolidated billing)
          - Sid: AllowOrganizationsReadAccess
            Effect: Allow
            Action:
              - organizations:ListAccounts
              - organizations:DescribeAccount
              - organizations:DescribeOrganization
            Resource: '*'

          # Support for Account Information
          - Sid: AllowAccountInfo
            Effect: Allow
            Action:
              - iam:GetAccountSummary
              - iam:SimulatePrincipalPolicy
              - sts:GetCallerIdentity
            Resource: '*'

          # Waste Detection - Read-only access to detect unused/underutilized resources
          # Covers 46+ detectors including: EC2, EBS, RDS, Network, Lambda, S3, DynamoDB, ElastiCache,
          # Redshift, OpenSearch, ECS, CloudWatch, SecretsManager, KMS, EMR, SageMaker, Kinesis,
          # Glue, EFS, FSx, ECR, APIGateway, CloudFront, Route53, GlobalAccelerator, MSK, MQ,
          # Neptune, DocumentDB, Timestream, QLDB, WorkSpaces, Lightsail, ElasticBeanstalk,
          # TransferFamily, StepFunctions, AppSync, CloudTrail, AWS Backup
          # Plus: AWS Compute Optimizer (ML-backed rightsizing), RI/Savings Plans recommendations
          
          - Sid: AllowWasteDetectionCompute
            Effect: Allow
            Action:
              # EC2
              - ec2:DescribeInstances
              - ec2:DescribeInstanceTypes
              - ec2:DescribeVolumes
              - ec2:DescribeSnapshots
              - ec2:DescribeImages
              - ec2:DescribeAddresses
              - ec2:DescribeNatGateways
              # Lambda
              - lambda:ListFunctions
              - lambda:GetFunction
              - lambda:ListProvisionedConcurrencyConfigs
              # ECS
              - ecs:ListClusters
              - ecs:DescribeClusters
              - ecs:ListServices
              - ecs:DescribeServices
              - ecs:DescribeTaskDefinition
              - ecs:ListTaskDefinitions
              - ecs:ListTagsForResource
              # EKS
              - eks:ListClusters
              - eks:DescribeCluster
              # Lightsail
              - lightsail:GetInstances
              - lightsail:GetStaticIps
              - lightsail:GetDisks
              - lightsail:GetInstanceSnapshots
              - lightsail:GetLoadBalancers
              - lightsail:GetRelationalDatabases
              # Elastic Beanstalk
              - elasticbeanstalk:DescribeEnvironments
              - elasticbeanstalk:DescribeConfigurationSettings
              - elasticbeanstalk:DescribeInstancesHealth
            Resource: '*'

          - Sid: AllowWasteDetectionStorage
            Effect: Allow
            Action:
              # S3
              - s3:ListAllMyBuckets
              - s3:GetBucketLocation
              - s3:GetBucketTagging
              - s3:ListBucket
              - s3:ListBucketMultipartUploads
              - s3:GetLifecycleConfiguration
              # EFS
              - elasticfilesystem:DescribeFileSystems
              - elasticfilesystem:DescribeMountTargets
              # FSx
              - fsx:DescribeFileSystems
              - fsx:DescribeBackups
              # ECR
              - ecr:DescribeRepositories
              - ecr:DescribeImages
              # AWS Backup
              - backup:ListBackupVaults
              - backup:ListRecoveryPointsByBackupVault
              - backup:ListBackupPlans
              - backup:GetBackupPlan
              - backup:ListBackupSelections
              - backup:GetBackupSelection
              - backup:ListCopyJobs
            Resource: '*'

          - Sid: AllowWasteDetectionDatabases
            Effect: Allow
            Action:
              # RDS (also covers Neptune and DocumentDB)
              - rds:DescribeDBInstances
              - rds:DescribeDBClusters
              - rds:DescribeDBSnapshots
              - rds:DescribeDBClusterSnapshots
              - rds:ListTagsForResource
              # DynamoDB
              - dynamodb:ListTables
              - dynamodb:DescribeTable
              # ElastiCache
              - elasticache:DescribeReplicationGroups
              - elasticache:DescribeCacheClusters
              - elasticache:ListTagsForResource
              # Redshift
              - redshift:DescribeClusters
              # OpenSearch
              - es:ListDomainNames
              - es:DescribeDomain
              - es:DescribeDomains
              # Timestream
              - timestream:ListDatabases
              - timestream:ListTables
              # QLDB
              - qldb:ListLedgers
            Resource: '*'

          - Sid: AllowWasteDetectionNetworking
            Effect: Allow
            Action:
              # ELB
              - elasticloadbalancing:DescribeLoadBalancers
              - elasticloadbalancing:DescribeTargetGroups
              - elasticloadbalancing:DescribeTargetHealth
              # API Gateway
              - apigateway:GET
              # CloudFront
              - cloudfront:ListDistributions
              # Route 53
              - route53:ListHostedZones
              # Global Accelerator
              - globalaccelerator:ListAccelerators
              - globalaccelerator:ListListeners
              - globalaccelerator:ListEndpointGroups
            Resource: '*'

          - Sid: AllowWasteDetectionAnalyticsML
            Effect: Allow
            Action:
              # EMR
              - elasticmapreduce:ListClusters
              - elasticmapreduce:DescribeCluster
              - elasticmapreduce:ListInstanceGroups
              - elasticmapreduce:ListSteps
              - elasticmapreduce:GetAutoTerminationPolicy
              - elasticmapreduce:DescribeStep
              # SageMaker
              - sagemaker:ListNotebookInstances
              - sagemaker:DescribeNotebookInstance
              - sagemaker:ListEndpoints
              - sagemaker:DescribeEndpoint
              - sagemaker:DescribeEndpointConfig
              # Kinesis
              - kinesis:ListStreams
              - kinesis:DescribeStreamSummary
              - kinesis:ListStreamConsumers
              - kinesis:DescribeStreamConsumer
              # Firehose
              - firehose:ListDeliveryStreams
              - firehose:DescribeDeliveryStream
              # Glue
              - glue:GetDevEndpoints
            Resource: '*'

          - Sid: AllowWasteDetectionMessaging
            Effect: Allow
            Action:
              # MSK (Kafka)
              - kafka:ListClusters
              # MQ (RabbitMQ/ActiveMQ)
              - mq:ListBrokers
              - mq:DescribeBroker
            Resource: '*'

          - Sid: AllowWasteDetectionIntegration
            Effect: Allow
            Action:
              # Step Functions
              - states:ListStateMachines
              - states:ListExecutions
              # AppSync
              - appsync:ListGraphqlApis
              - appsync:GetApiCache
              # Transfer Family
              - transfer:ListServers
              - transfer:ListUsers
            Resource: '*'

          - Sid: AllowWasteDetectionManagement
            Effect: Allow
            Action:
              # CloudWatch
              - cloudwatch:GetMetricStatistics
              - cloudwatch:GetMetricData
              - cloudwatch:ListDashboards
              - logs:DescribeLogGroups
              - logs:DescribeLogStreams
              # CloudTrail (for detecting duplicate trails and storage waste)
              - cloudtrail:DescribeTrails
              - cloudtrail:GetTrailStatus
              - cloudtrail:GetEventSelectors
              # Secrets Manager
              - secretsmanager:ListSecrets
              # KMS
              - kms:ListKeys
              - kms:DescribeKey
              - kms:ListAliases
              # WorkSpaces
              - workspaces:DescribeWorkspaces
              - workspaces:DescribeWorkspacesConnectionStatus
              - workspaces:DescribeWorkspaceBundles
              - workspaces:DescribeWorkspacesPools
            Resource: '*'

          # DynamoDB Auto Scaling detection
          - Sid: AllowWasteDetectionAutoScaling
            Effect: Allow
            Action:
              - application-autoscaling:DescribeScalableTargets
              - application-autoscaling:DescribeScalingPolicies
            Resource: '*'

          # ECR lifecycle policy detection
          - Sid: AllowWasteDetectionECRLifecycle
            Effect: Allow
            Action:
              - ecr:GetLifecyclePolicy
            Resource: '*'

          # Glue jobs and crawlers detection
          - Sid: AllowWasteDetectionGlueJobs
            Effect: Allow
            Action:
              - glue:GetJobs
              - glue:GetCrawlers
              - glue:GetJobRuns
              - glue:GetCrawlerMetrics
            Resource: '*'

Outputs:
  CloudWiseRoleArn:
    Description: 'COPY THIS: CloudWise Access Role - paste this into CloudWise account setup'
    Value: !GetAtt CloudWiseAccessRole.Arn
    Export:
      Name: !Sub '${AWS::StackName}-CloudWiseRoleArn'

  BucketName:
    Description: 'COPY THIS: S3 Bucket name for cost processing (required)'
    Value: !Ref CostReportsBucket
    Export:
      Name: !Sub '${AWS::StackName}-BucketName'

  CURReportName:
    Description: 'COPY THIS: Cost and Usage Report name (required)'
    Value: !Sub 'CloudWiseReports-${AWS::AccountId}'
    Export:
      Name: !Sub '${AWS::StackName}-CURReportName'

  SetupInstructions:
    Description: '🎉 Setup Complete - Next Steps'
    Value: !Sub
      - |
        Your AWS account is now ready for CloudWise! 🚀
        
        📋 COPY THESE THREE VALUES TO CLOUDWISE (ALL REQUIRED):
        
        1. CloudWise Access Role:
           ${CloudWiseAccessRole.Arn}
        
        2. S3 Bucket Name (Auto-generated):
           ${CostReportsBucket}
        
        3. CUR Report Name:
           CloudWiseReports-${AWS::AccountId}
        
        ✅ What was AUTOMATICALLY configured for you:
        • ✨ Cost and Usage Reports (${CURLabel}) - no manual setup needed!
        • 🪣 S3 bucket with unique auto-generated name and proper permissions
        • 🔐 IAM role with secure CloudWise access permissions
        • 📊 Daily cost reports in CSV format (efficient & fast)
        • 🛡️ Security restrictions (IP allowlists, external ID validation)
        • 🔄 Automatic lifecycle rules (90-day retention)
        • 🔍 Waste Detection - find unused resources across your account
        
        ⏰ First cost report will be available in 24 hours
        📊 Cost reports location: s3://${CostReportsBucket}/${S3Prefix}/
        💰 Start seeing 99% cost reduction vs Cost Explorer API immediately!
        
        💡 Next: Return to CloudWise and paste the Role ARN in the "CloudWise Access Role" field!
      - CURLabel: !If [IsCUR1, "CUR 1.0 Legacy", "CUR 2.0 Data Exports"]
        S3Prefix: !If [IsCUR1, "daily-v1", "daily-v2"]