// Confidence Engine — Manual Jenkins Deployment Pipeline
//
// Trigger: manually, via "Build with Parameters"
// Parameter: GIT_REF (string) — the Git ref to deploy
//
// Pre-requisites in Jenkins:
//   1. SSH credential of type "SSH Username with private key"
//      named 'confidence-engine-deploy-ssh' that can reach
//      CT 112 (confidence-engine / 192.168.68.73).
//      The username from the credential is used for SSH login.
//   2. The Gitea repository configured in the job SCM section.

pipeline {
    agent any

    parameters {
        string(
            name: 'GIT_REF',
            defaultValue: '',
            description: 'Git ref to deploy (branch name, tag, or full commit SHA). Leave blank to fail.'
        )
    }

    environment {
        TARGET_HOST      = '192.168.68.73'
        DEPLOY_DIR       = '/opt/confidence-engine'
        HEALTH_URL       = 'http://127.0.0.1:3000/api/health'
    }

    stages {

        stage('Resolve') {
            steps {
                script {
                    def ref = params.GIT_REF.trim()
                    if (!ref || ref.isEmpty()) {
                        error 'GIT_REF parameter is blank or empty. Provide a Git ref to deploy.'
                    }

                    echo "Requested ref: ${ref}"

                    // Resolve the ref to an exact SHA via Gitea remote.
                    // If ref is already a 40-char hex SHA, use it directly.
                    def shaPattern = ~/^[0-9a-fA-F]{40}$/
                    def resolvedSha
                    if (ref ==~ shaPattern) {
                        resolvedSha = ref
                        echo "Provided ref is a full commit SHA: ${resolvedSha}"
                    } else {
                        // For branches/tags, look up on origin
                        resolvedSha = sh(
                            script: "git ls-remote origin refs/heads/${ref} refs/tags/${ref} 2>/dev/null | awk '/^[0-9a-f]/{print \$1; exit}'",
                            returnStdout: true
                        ).trim()

                        if (!resolvedSha || resolvedSha.length() != 40) {
                            // Broader fallback — might match partial SHA or ref prefix
                            resolvedSha = sh(
                                script: "git ls-remote origin ${ref} 2>/dev/null | awk '/^[0-9a-f]/{print \$1; exit}'",
                                returnStdout: true
                            ).trim()

                            if (!resolvedSha || resolvedSha.length() != 40) {
                                error "Cannot resolve '${ref}' to a commit SHA on origin. Check the ref and repository configuration."
                            }
                        }
                    }

                    echo "Resolved SHA: ${resolvedSha}"
                    env.DEPLOY_SHA = resolvedSha
                }
            }
        }

        stage('Deploy') {
            steps {
                script {
                    // Run the deployment script on CT 112 via SSH
                    withCredentials([sshUserPrivateKey(
                        credentialsId: 'confidence-engine-deploy-ssh',
                        keyFileVariable: 'SSH_KEY',
                        usernameVariable: 'SSH_USER'
                    )]) {
                        sh '''
                            ssh \
                                -i "$SSH_KEY" \
                                -o StrictHostKeyChecking=yes \
                                "$SSH_USER@$TARGET_HOST" \
                                bash -s -- "$DEPLOY_SHA" "$DEPLOY_DIR" "$HEALTH_URL" \
                                < "$WORKSPACE/scripts/deploy-production.sh"
                        '''
                    }
                }
            }
        }

        stage('Verify/result') {
            steps {
                script {
                    echo "Deployment stages completed. Check the Deploy stage output above for success/failure."
                }
            }
        }
    }

    post {
        failure {
            echo 'DEPLOYMENT FAILED — check the Deploy stage logs for details.'
        }
        success {
            echo "DEPLOYMENT SUCCEEDED — deployed SHA: ${env.DEPLOY_SHA}"
        }
    }
}
