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
                . venv/bin/activate
                pip install -U atproto fastfeedparser beautifulsoup4 httpx arrow charset-normalizer Pillow
                '''
            }
        }

        stage('Run Script') {
            steps {
                // Securely inject Jenkins credentials as environment variables
                withCredentials([
                    string(credentialsId: 'BSKY_324_HANDLE', variable: 'BSKY_324_HANDLE'),
                    string(credentialsId: 'BSKY_324_USERNAME', variable: 'BSKY_324_USERNAME'),
                    string(credentialsId: 'BSKY_324_APP_PASSWORD', variable: 'BSKY_324_APP_PASSWORD')
                ]) {
                    sh '''
                    # Activate the exact same virtual environment so Python finds the packages
                    . venv/bin/activate
                    
                    # Run the script with the RSS URL, credentials, and custom service flag
                    python3 rss2bsky.py \
                        "https://api.3cat.cat/noticies?_format=rss&origen=frontal&frontal=n324-portada-noticia&version=2.0" \
                        "$BSKY_324_HANDLE" \
                        "$BSKY_324_USERNAME" \
                        "$BSKY_324_APP_PASSWORD" \
                        --service "https://eurosky.social"
                    '''
                }
            }
        }
    }
}
