#!/usr/bin/env bash
# Sourced by Jeannie. This diagnosis and its single optional mitigation are
# deliberately limited to the Debian-hosted Gitea Actions runner.

doctor_runner_report() {
    local app deployment host configured revision head state load rc=0 answer baseline=false
    local kubeconfig="${KUBECONFIG_PATH}"
    printf 'Gitea Actions runner\n====================\n'
    printf 'Profile: %s (%s)\n\n' "${LAB_CLUSTER_PROFILE:-unknown}" "${LAB_CLUSTER_RUNTIME:-unknown}"

    printf 'Evidence from the selected cluster:\n'
    printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application gitea-runner -o jsonpath=\047{.status.health.status}{" "}{.status.sync.status}{" "}{.status.sync.revision}\047\n' "${kubeconfig}"
    app="$(kubectl --kubeconfig "${kubeconfig}" --request-timeout=10s -n argocd get application gitea-runner -o jsonpath='{.status.health.status}{" "}{.status.sync.status}{" "}{.status.sync.revision}' 2>&1)" || rc=1
    printf '%s\n' "${app}"
    printf '$ kubectl --kubeconfig %q --request-timeout=10s -n gitea-runner get deployment gitea-runner -o jsonpath=\047desired={.spec.replicas} ready={.status.readyReplicas} available={.status.availableReplicas}\047\n' "${kubeconfig}"
    deployment="$(kubectl --kubeconfig "${kubeconfig}" --request-timeout=10s -n gitea-runner get deployment gitea-runner -o jsonpath='desired={.spec.replicas} ready={.status.readyReplicas} available={.status.availableReplicas}' 2>&1)" || rc=1
    printf '%s\n\n' "${deployment}"

    printf 'Evidence from the Debian host:\n'
    printf '$ systemctl show homelab-gitea-runner.service -p LoadState -p ActiveState\n'
    host="$(systemctl show homelab-gitea-runner.service -p LoadState -p ActiveState 2>&1)" || rc=1
    printf '%s\n\n' "${host}"
    state="$(printf '%s\n' "${host}" | sed -n 's/^ActiveState=//p')"
    load="$(printf '%s\n' "${host}" | sed -n 's/^LoadState=//p')"
    read -r _ _ revision <<<"${app}"
    head="$(git -C "${REPO_ROOT}" rev-parse HEAD 2>/dev/null || true)"
    configured="$(git -C "${REPO_ROOT}" show HEAD:apps/gitea-runner/deployment.yaml 2>/dev/null | awk '/^  replicas:/ && !seen {print $2; seen=1}')" || configured=""

    if [[ "${rc}" != 0 ]]; then
        echo 'Diagnosis: A required check failed; the runner state cannot be established from this report.'
        echo 'No mitigation is proposed until access to the failed check is restored.'
        return 1
    fi
    if [[ "${deployment}" == desired=0\ * && "${configured}" == 0 && -n "${revision}" && "${revision}" == "${head}" && "${app}" == *" Synced "* ]]; then
        baseline=true
        printf 'Diagnosis: Argo CD reports %s, but the synced repository intentionally sets the Kubernetes runner to zero replicas. The Debian service is the intended CI runner.\n' "${app%% *}"
        printf '$ git -C %q show HEAD:apps/gitea-runner/deployment.yaml | awk \047/^  replicas:/ && !seen {print $2; seen=1}\047\n%s\n' "${REPO_ROOT}" "${configured}"
    else
        echo 'Diagnosis: The Argo CD state and live deployment are shown above. The local zero-replica configuration cannot be confirmed as the synced revision, so its intent is not assumed.'
    fi

    if [[ "${load}" == loaded && "${state}" == active ]]; then
        echo 'The Debian CI runner service is active; this alone does not verify registration or job execution.'
        if [[ ( "${baseline}" == true && "${app}" == "Progressing Synced "* ) || "${app}" == "Healthy Synced "* ]]; then
            echo 'No runner restart or Kubernetes scaling is indicated by these checks.'
            return 0
        fi
        echo 'The Kubernetes application still needs investigation. No specific mitigation is established.'
        return 1
    fi
    if [[ "${load}" != loaded ]]; then
        echo 'The Debian runner service is not loaded. Inspect its installation before choosing a repair.'
        echo 'Read-only check: systemctl status homelab-gitea-runner.service --no-pager -l'
        return 1
    fi
    if [[ "${state}" != inactive && "${state}" != failed ]]; then
        printf 'The Debian runner service is %s. Inspect its state before choosing a repair.\n' "${state:-unknown}"
        echo 'Read-only check: systemctl status homelab-gitea-runner.service --no-pager -l'
        return 1
    fi
    printf 'The Debian CI runner service is %s. Starting it may restore job execution; this does not verify runner registration or job execution.\n' "${state}"
    echo 'Proposed mitigation: sudo -n systemctl start homelab-gitea-runner.service'
    if [[ ! -t 0 || ! -t 1 ]]; then
        echo 'Approval is required; run the command above on Debian or rerun this doctor in an interactive terminal.'
        return 1
    fi
    read -r -p 'Apply this mitigation? [y/N] ' answer || answer=""
    if [[ "${answer}" != y && "${answer}" != Y ]]; then
        echo 'Mitigation not applied.'
        return 1
    fi
    if ! sudo -n systemctl start homelab-gitea-runner.service; then
        echo 'The start command failed. Inspect the service journal.'
        return 1
    fi
    echo '$ systemctl is-active homelab-gitea-runner.service'
    systemctl is-active homelab-gitea-runner.service || return 1
}
