pipeline {
 agent {
        kubernetes {
            yaml """
apiVersion: v1
kind: Pod
spec:
  containers:
    - name: python-39-slim-buster-build
      image: python:3.9 
      command:
        - cat
      tty: true
      securityContext:
        privileged: true
        runAsUser: 0
   
    - name: jnlp
      image: jenkins/inbound-agent:latest
      args: ['\$(JENKINS_SECRET)', '\$(JENKINS_NAME)']
      securityContext:
        privileged: true
        runAsUser: 0
    - name: podman
      image: quay.io/podman/stable
      command:
        - cat
      tty: true
      securityContext:
        privileged: true
        runAsUser: 0
    - name: kubectl
      image: dtzar/helm-kubectl
      command:
        - cat
      tty: true
      securityContext:
        privileged: true
        runAsUser: 0
"""
        }
    } 
    parameters {

        string(name: 'CHASE_USER', defaultValue: '', description: 'Chase username')
        string(name: 'CHASE_PASS', defaultValue: '', description: 'Chase password')
    }
    

  environment {
    REGISTRY = "docker.io/agalyadoss"
    IMAGE = "ledger"
    VENV_DIR = 'venv'
    OUTPUTDIR = 'results'
    CHASE_USER= "${params.CHASE_USER}"
    CHASE_PASS= "${params.CHASE_PASS}"
  }

  stages {
    stage('Generate Version') {
            steps {
                script {
                    def arch = sh(script: 'uname -m', returnStdout: true).trim()
                    def now = new Date()
                    def year = now.format("yyyy")
                    def month = now.format("MM")
                    def weekOfYear = now[Calendar.WEEK_OF_YEAR]  // Week of Year
                    VERSION = "${year}.${month}.${weekOfYear}.${BUILD_NUMBER}.${arch}"
                    echo "Version: ${VERSION}"
                    
                    // Auto-generate version if DOCKER_TAG param is blank
                    if (params.DOCKER_TAG?.trim()) {
                        TAG = params.DOCKER_TAG
                        echo "Using provided DOCKER_TAG: ${TAG}"
                    } else {
                        TAG = "${year}.${month}.${weekOfYear}.${BUILD_NUMBER}.${arch}"
                        echo "Auto-generated version: ${TAG}"
                    }
                }
            }
        }

        stage('Print Build Number') {
            steps {
                echo "Current Build Number: ${VERSION}"
            }
        }
    

stage('Chechout Repo cockoo') {
            steps {
                container('python-39-slim-buster-build') {
                    withCredentials([usernamePassword(credentialsId: 'H000146',
                                                     usernameVariable: 'GIT_USER',
                                                     passwordVariable: 'GIT_PASS')]) {
                        sh """
                        git clone https://${GIT_USER}:${GIT_PASS}@gitbucket.heaerie.com/git/agalyadoss/ledger.git
                        cd ledger && git checkout main
                        
                        git config user.name "Jenkins CI"
                        git config user.email "jenkins@heaerie.com"
                        git tag ${VERSION}
                        git push https://${GIT_USER}:${GIT_PASS}@gitbucket.heaerie.com/git/agalyadoss/ledger.git ${VERSION}
                     
                        """
                    }
                }
            }
        }

    stage('Setup Python') {
       steps {
        container('python-39-slim-buster-build') {
 
        sh """
        ls -lart
        pwd
        cd ledger
        python3 -m venv $VENV_DIR
        . $VENV_DIR/bin/activate 
        python3 -m pip install --upgrade pip
        python3 -m pip install robotframework selenium robotframework-seleniumlibrary webdriver-manager || true
        if [ -f requirements.txt ]; then pip install -r requirements.txt || true; fi
        """
        }
      }
    }

    

    stage('Create PVC') {
      steps {
         container('python-39-slim-buster-build') {
        // Apply PVC manifest if kubectl is available
        sh "if command -v kubectl >/dev/null 2>&1; then kubectl apply -f k8s/pvc-chrome-profile.yaml || true; kubectl wait --for=condition=bound pvc/chrome-profile-pvc --timeout=60s || true; else echo 'kubectl not found, skipping PVC creation'; fi"
       }
      }
    }

    stage('Run Robot Tests') {
      steps {
        container('python-39-slim-buster-build') {
        sh '. $VENV_DIR/bin/activate && mkdir -p ${OUTPUTDIR} && ./jenkins/run_robot.sh'
        }
      }
      post {
        always {
          archiveArtifacts artifacts: 'results/**', fingerprint: true
        }
      }
    }
  }

  post {
    failure {
      echo 'Robot tests failed. See archived artifacts in results/ for details.'
    }
  }
}
