pipeline {
    agent any
    
    options {
        timeout(time: 15, unit: 'MINUTES')
        timestamps()
        buildDiscarder(logRotator(numToKeepStr: '10'))
        disableConcurrentBuilds()
    }
    
    triggers {
        // 'H' balances the load on Jenkins, running roughly every 30 minutes
        cron('H/30 * * * *')
    }

    stages {
        stage('Checkout Code') {
            steps {
                checkout scm
            }
        }

        stage('Setup Python & Install Dependencies') {
            steps {
                sh '''
                # Create a virtual environment named 'venv'
                python3 -m venv venv
                
                # Activate it and install the required packages for the RSS script
                . venv/bin/activate
                pip install atproto fastfeedparser beautifulsoup4 httpx arrow charset-normalizer Pillow
                '''
            }
        }

        stage('Run Script') {
            steps {
                // Securely inject Jenkins credentials as environment variables
                withCredentials([
                    string(credentialsId: 'BSKY_CRUNCHYROLL_HANDLE', variable: 'BSKY_CRUNCHYROLL_HANDLE'),
                    string(credentialsId: 'TWITTER_CRUNCHY_EMAIL', variable: 'TWITTER_CRUNCHY_EMAIL'),
                    string(credentialsId: 'BSKY_CRUNCHYROLL_APP_PASSWORD', variable: 'BSKY_CRUNCHYROLL_APP_PASSWORD')
                ]) {
                    sh '''
                    # Activate the virtual environment
                    . venv/bin/activate
                    
                    # Run the RSS script with positional arguments
                    python3 rss2bsky.py \
                        "https://cr-news-api-service.prd.crunchyrollsvc.com/v1/es-ES/rss" \
                        "$BSKY_CRUNCHYROLL_HANDLE" \
                        "$TWITTER_CRUNCHY_EMAIL" \
                        "$BSKY_CRUNCHYROLL_APP_PASSWORD" \
                        --service "https://eurosky.social" \
                        --lang es
                    '''
                }
            }
        }
    }
}