AWSTemplateFormatVersion: '2010-09-09'
Description: 'AWS OIDC Infrastructure for mypylogger PyPI Publishing via GitHub Actions'

Parameters:
  GitHubOrg:
    Type: String
    Description: GitHub organization or username
    Default: 'your-github-org'
  
  GitHubRepo:
    Type: String
    Description: GitHub repository name
    Default: 'mypylogger'
  
  PyPIToken:
    Type: String
    Description: PyPI API token for publishing
    NoEcho: true
    MinLength: 1

Resources:
  # OIDC Identity Provider for GitHub Actions
  GitHubOIDCProvider:
    Type: AWS::IAM::OIDCIdentityProvider
    Properties:
      Url: https://token.actions.githubusercontent.com
      ClientIdList:
        - sts.amazonaws.com
      ThumbprintList:
        - 6938fd4d98bab03faadb97b34396831e3780aea1
        - 1c58a3a8518e8759bf075b76b750d4f2df264fcd
      Tags:
        - Key: Purpose
          Value: GitHubActions-PyPI-Publishing
        - Key: Project
          Value: mypylogger

  # IAM Role for GitHub Actions PyPI Publishing
  GitHubActionsRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub '${AWS::StackName}-github-actions-pypi-role'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Federated: !Ref GitHubOIDCProvider
            Action: sts:AssumeRoleWithWebIdentity
            Condition:
              StringEquals:
                'token.actions.githubusercontent.com:aud': sts.amazonaws.com
              StringLike:
                'token.actions.githubusercontent.com:sub': !Sub 'repo:${GitHubOrg}/${GitHubRepo}:*'
      ManagedPolicyArns:
        - !Ref PyPISecretsPolicy
      Tags:
        - Key: Purpose
          Value: GitHubActions-PyPI-Publishing
        - Key: Project
          Value: mypylogger

  # Policy for accessing PyPI token from Secrets Manager
  PyPISecretsPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub '${AWS::StackName}-pypi-secrets-policy'
      Description: 'Policy for accessing PyPI token from AWS Secrets Manager'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - secretsmanager:GetSecretValue
            Resource: !Ref PyPITokenSecret
          - Effect: Allow
            Action:
              - secretsmanager:DescribeSecret
            Resource: !Ref PyPITokenSecret

  # AWS Secrets Manager secret for PyPI token
  PyPITokenSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Name: !Sub '${AWS::StackName}/pypi-token'
      Description: 'PyPI API token for mypylogger package publishing'
      SecretString: !Sub |
        {
          "token": "${PyPIToken}",
          "repository": "https://upload.pypi.org/legacy/",
          "package": "mypylogger"
        }
      Tags:
        - Key: Purpose
          Value: PyPI-Publishing
        - Key: Project
          Value: mypylogger

  # Secret rotation configuration (optional)
  PyPITokenSecretRotation:
    Type: AWS::SecretsManager::RotationSchedule
    Properties:
      SecretId: !Ref PyPITokenSecret
      RotationLambdaArn: !GetAtt PyPITokenRotationLambda.Arn
      RotationRules:
        AutomaticallyAfterDays: 90

  # Lambda function for token rotation (placeholder)
  PyPITokenRotationLambda:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub '${AWS::StackName}-pypi-token-rotation'
      Runtime: python3.9
      Handler: index.lambda_handler
      Role: !GetAtt PyPITokenRotationRole.Arn
      Code:
        ZipFile: |
          import json
          import boto3
          
          def lambda_handler(event, context):
              # Placeholder for PyPI token rotation logic
              # In production, this would handle automatic token rotation
              print("PyPI token rotation triggered")
              return {
                  'statusCode': 200,
                  'body': json.dumps('Token rotation completed')
              }
      Tags:
        - Key: Purpose
          Value: PyPI-Token-Rotation
        - Key: Project
          Value: mypylogger

  # IAM Role for Lambda rotation function
  PyPITokenRotationRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub '${AWS::StackName}-pypi-rotation-role'
      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: SecretsManagerRotationPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - secretsmanager:UpdateSecret
                  - secretsmanager:GetSecretValue
                  - secretsmanager:PutSecretValue
                Resource: !Ref PyPITokenSecret

Outputs:
  GitHubActionsRoleArn:
    Description: 'ARN of the IAM role for GitHub Actions'
    Value: !GetAtt GitHubActionsRole.Arn
    Export:
      Name: !Sub '${AWS::StackName}-github-actions-role-arn'

  PyPITokenSecretArn:
    Description: 'ARN of the PyPI token secret'
    Value: !Ref PyPITokenSecret
    Export:
      Name: !Sub '${AWS::StackName}-pypi-token-secret-arn'

  PyPITokenSecretName:
    Description: 'Name of the PyPI token secret'
    Value: !Ref PyPITokenSecret
    Export:
      Name: !Sub '${AWS::StackName}-pypi-token-secret-name'

  OIDCProviderArn:
    Description: 'ARN of the GitHub OIDC provider'
    Value: !Ref GitHubOIDCProvider
    Export:
      Name: !Sub '${AWS::StackName}-oidc-provider-arn'