pipeline {
    agent any

    options {
        timeout(time: 20, unit: 'MINUTES')
        timestamps()
        buildDiscarder(logRotator(numToKeepStr: '10'))
        disableConcurrentBuilds()
    }

    triggers {
        cron('H/30 * * * *')
    }

    stages {

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

        stage('Setup Python & Install Dependencies') {
            steps {
                sh '''
                    set -e
                    cd "$WORKSPACE"

                    # Crea el venv
                    python3 -m venv venv

                    # Usa sempre python3 -m pip, mai el binari pip directament
                    "$WORKSPACE/venv/bin/python3" -m pip install --upgrade pip wheel setuptools

                    "$WORKSPACE/venv/bin/python3" -m pip install -U \
                        atproto \
                        playwright \
                        playwright-stealth \
                        httpx \
                        arrow \
                        python-dotenv \
                        moviepy \
                        beautifulsoup4 \
                        charset-normalizer \
                        Pillow \
                        grapheme \
                        yt-dlp \
                        curl-cffi

                    # Sanity checks
                    "$WORKSPACE/venv/bin/python3" -c "import atproto;   print('atproto    OK')"
                    "$WORKSPACE/venv/bin/python3" -c "import playwright; print('playwright OK')"
                    "$WORKSPACE/venv/bin/python3" -c "import yt_dlp;     print('yt_dlp     OK')"
                    "$WORKSPACE/venv/bin/python3" -c "import curl_cffi;  print('curl_cffi  OK')"

                    # Playwright browser binaries
                    PLAYWRIGHT_BROWSERS_PATH=/var/jenkins_home/.playwright-browsers \
                        "$WORKSPACE/venv/bin/python3" -m playwright install chromium
                '''
            }
        }

        // ─────────────────────────────────────────────
        //  3. Run the bot
        // ─────────────────────────────────────────────
        stage('Run Script') {
            steps {
                withCredentials([
                    string(
                        credentialsId: 'TIKTOK_3CATCAMPUS_HANDLE',
                        variable:      'TIKTOK_3CATCAMPUS_HANDLE'
                    ),
                    string(
                        credentialsId: 'BSKY_3CAT_HANDLE',
                        variable:      'BSKY_3CAT_HANDLE'
                    ),
                    string(
                        credentialsId: 'BSKY_3CAT_APP_PASSWORD',
                        variable:      'BSKY_3CAT_APP_PASSWORD'
                    ),
                    file(
                        credentialsId: 'TIKTOK_COOKIES_JSON',
                        variable:      'TIKTOK_COOKIES_FILE'
                    )
                ]) {
                    sh '''
                        set -e

                        # Inject the secret cookies file into the workspace
                        cp "$TIKTOK_COOKIES_FILE" tiktok_cookies.json

                        . venv/bin/activate
                        python3 tiktok2bsky.py \
                            --tiktok-handle     "$TIKTOK_3CATCAMPUS_HANDLE" \
                            --bsky-handle       "$BSKY_3CAT_HANDLE" \
                            --bsky-app-password "$BSKY_3CAT_APP_PASSWORD" \
                            --bsky-base-url     https://eurosky.social \
                            --bsky-langs        ca \
                            --cookies-path      tiktok_cookies.json
                    '''
                }
            }
        }
    }

    // ─────────────────────────────────────────────
    //  Post actions
    // ─────────────────────────────────────────────
    post {

        always {
            // Archive logs, state, and any debug screenshots
            archiveArtifacts(
                artifacts:         '*.log, *.json, screenshot_*.png',
                allowEmptyArchive: true
            )

            // Remove injected cookies file — never leave on disk between runs
            sh 'rm -f tiktok_cookies.json || true'
        }

        success {
            echo '✅ Sync cycle completed successfully.'
        }

        failure {
            echo '❌ Sync cycle failed — check archived logs and screenshots.'
        }

        unstable {
            echo '⚠️ Sync cycle finished with warnings.'
        }
    }
}