#!/usr/bin/env bash
# Sourced by Jeannie; all probes are read-only.

doctor_focus_usage() {
    cat <<'EOF'
Usage: ./jeannie doctor {oci|rpi|opi5|debian|cluster} [ITEM] [options]
       ./jeannie doctor ITEM [options]

Diagnose one inventory area. Optionally select an exact check, Argo CD
application, Compose project/service, or unambiguous Compose service name
shown by status. There is no all-area doctor.

  --ai            Request an evidence-validated AI explanation (text only;
                  enabled by default when diagnosing an item).
  --no-local-rca  Disable the AI explanation.
  --json          Return the structured diagnostic report.
  --details       Show supporting evidence.
  --all           Include healthy checks (default).
  --item NAME     Alternative to positional ITEM.
  --repair-k3s   Recover a confirmed stale Orange Pi K3s storage mount.
                  This changes host mounts and restarts K3s; local CLI only.

Examples:
  ./jeannie doctor rpi
  ./jeannie doctor gitea-runner
  ./jeannie doctor cluster gitea-runner --ai
  ./jeannie remote doctor debian --item homelab-gitea/gitea
EOF
}

doctor_focus_https() {
    curl -fsS -o /dev/null --connect-timeout 3 --max-time 8 "${LAB_PUBLIC_URL%/}/edge-health"
}

doctor_focus_k3s_storage_report() {
    local evidence summary severity
    if ! evidence="$(python3 "${REPO_ROOT}/scripts/doctor-k3s-storage.py" inspect 2>&1)"; then
        report_ui_emit warn "Orange Pi diagnostics" "K3s storage evidence" "Cannot inspect K3s storage" "${evidence}"
        return 0
    fi
    if printf '%s' "${evidence}" | python3 -c 'import json,sys; sys.exit(0 if json.load(sys.stdin).get("stale_readonly_mount") else 1)'; then
        summary="Stale read-only K3s mount; the mounted device is no longer detected"
        severity=warn
    else
        summary="No stale read-only K3s mount detected in this snapshot"
        severity=ok
    fi
    report_ui_emit "${severity}" "Orange Pi diagnostics" "K3s storage evidence" "${summary}" "${evidence}" "./jeannie doctor opi5 --repair-k3s"
}

doctor_focus_application_fetch() {
    local name="$1"
    [[ "${name}" =~ ^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$ ]] || { echo "Invalid application name" >&2; return 1; }
    kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n argocd get application "${name}" --ignore-not-found -o json 2>/dev/null
}

doctor_focus_application_lookup() {
    local name="$1" snapshot row
    [[ "${name}" =~ ^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$ ]] || return 0
    snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || {
        report_ui_emit warn "Item lookup" "Argo CD lookup" "Cannot query selected cluster" ""; return 0;
    }
    [[ -n "${snapshot}" ]] || return 0
    row="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --report 2>&1)" || {
        report_ui_emit warn "Item lookup" "Argo CD lookup" "Cannot interpret application" "${row}"; return 0;
    }
    printf '%s\n' "${row}" >>"${REPORT_UI_ROWS_FILE}"
}

doctor_focus_application_evidence() {
    local name="$1" snapshot deployments namespace deployment state count=0 failed=0
    snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || return 1
    printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application %q --ignore-not-found -o json | python3 %q\n' "${KUBECONFIG_PATH}" "${name}" "${REPO_ROOT}/scripts/doctor-application.py"
    printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" || return 1
    deployments="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployments)" || return 1
    while read -r namespace deployment; do
        [[ -n "${namespace}" && -n "${deployment}" ]] || continue
        ((count < 8)) || { echo "Additional deployments omitted"; break; }
        count=$((count + 1))
        printf '$ kubectl --kubeconfig %q --request-timeout=10s -n %q get deployment %q -o json | python3 %q --deployment\n' "${KUBECONFIG_PATH}" "${namespace}" "${deployment}" "${REPO_ROOT}/scripts/doctor-application.py"
        if state="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get deployment "${deployment}" -o json 2>/dev/null)"; then
            printf '%s' "${state}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployment || failed=1
        else
            echo "Deployment state unavailable."
            failed=1
        fi
    done <<<"${deployments}"
    return "${failed}"
}

doctor_focus_host_os_report() {
    local scope="$1" host="" user="" key="" area snapshot rows severity name detail command
    case "${scope}" in
        debian) area="Debian OS" ;;
        rpi) area="RPi4 OS"; host="${LAB_RPI_HOST:-}"; user="${LAB_RPI_USER:-}"; key="${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;;
        opi5) area="Orange Pi OS"; host="${LAB_PIMOX_HOST:-}"; user="${LAB_PIMOX_USER:-}"; key="${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;;
        oci) area="OCI edge OS"; host="${LAB_EDGE_TAILSCALE_IP:-}"; user="${LAB_EDGE_USER:-}"; key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}" ;;
        *) return 2 ;;
    esac
    command='
export LC_ALL=C
printf "%s\n" __JEANNIE_HOST_OS_V1__
printf "kernel="; uname -sr
printf "uptime_load="; uptime
printf "memory_kib="; awk '\''/MemTotal:/ {t=$2} /MemAvailable:/ {a=$2} END {print t, a}'\'' /proc/meminfo
printf "root_percent="; df -P / | awk '\''NR==2 {gsub(/%/, "", $5); print $5}'\''
printf "systemd="; systemctl is-system-running || true
'
    if [[ "${scope}" == debian ]]; then
        snapshot="$(timeout 12 bash -c "${command}" 2>&1)" || { report_ui_emit warn "${area}" "OS snapshot" "Cannot read OS state" "${snapshot}"; return 0; }
    else
        [[ -n "${host}" && -n "${user}" ]] || { report_ui_emit warn "${area}" "OS snapshot" "Host or user missing from inventory" ""; return 0; }
        snapshot="$(timeout 12 ssh -n -i "${key}" -o BatchMode=yes -o ConnectTimeout=3 \
            -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes "${user}@${host}" "${command}" 2>&1)" || {
            report_ui_emit warn "${area}" "OS snapshot" "Cannot read host OS state" "${snapshot}"; return 0;
        }
    fi
    rows="$(printf '%s\n' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-rpi-os.py" "${LAB_STATUS_DISK_USE_THRESHOLD:-85}" 2>&1)" || {
        report_ui_emit warn "${area}" "OS snapshot" "Cannot interpret host OS state" "${rows}"; return 0;
    }
    while IFS=$'\t' read -r severity name detail; do
        [[ -n "${severity}" ]] || continue
        report_ui_emit "${severity}" "${area}" "${name}" "${detail}" "${detail}"
    done <<<"${rows}"
}

doctor_focus_compose_evidence() {
    local scope="$1" check="$2" name host user key
    name="${check##* (}"
    name="${name%)}"
    [[ "${name}" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]] || { echo "Invalid container name" >&2; return 1; }
    local format='{{.State.Status}} restarts={{.RestartCount}} exit={{.State.ExitCode}} health={{if .State.Health}}{{.State.Health.Status}}{{else}}not-configured{{end}}'
    if [[ "${scope}" == debian ]]; then
        printf '$ sudo -n docker inspect --format %q %q\n' "${format}" "${name}"
        timeout 10 sudo -n docker inspect --format "${format}" "${name}"
        return
    fi
    case "${scope}" in
        rpi) host="${LAB_RPI_HOST:-}"; user="${LAB_RPI_USER:-}"; key="${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;;
        opi5) host="${LAB_PIMOX_HOST:-}"; user="${LAB_PIMOX_USER:-}"; key="${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;;
        oci) host="${LAB_EDGE_TAILSCALE_IP:-}"; user="${LAB_EDGE_USER:-}"; key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}" ;;
        *) return 2 ;;
    esac
    [[ -n "${host}" && -n "${user}" ]] || { echo "Host or user is missing from inventory" >&2; return 1; }
    printf '$ ssh -n -i %q -o BatchMode=yes -o ConnectTimeout=3 -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes %q %q\n' \
        "${key}" "${user}@${host}" "sudo -n docker inspect --format '${format}' '${name}'"
    timeout 10 ssh -n -i "${key}" -o BatchMode=yes -o ConnectTimeout=3 \
        -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes "${user}@${host}" \
        "sudo -n docker inspect --format '${format}' '${name}'"
}

doctor_focus_extra() {
    case "$1" in oci|rpi|opi5|debian) report_ui_enqueue doctor_focus_host_os_report "$1" ;; esac
    case "$1" in
        oci)
            if [[ -n "${LAB_PUBLIC_URL:-}" ]]; then
                report_ui_check warn "OCI edge diagnostics" "Public HTTPS certificate and health" "curl -v --max-time 8 '${LAB_PUBLIC_URL%/}/edge-health'" "" "" doctor_focus_https
            fi
            ;;
        rpi)
            report_ui_check warn "RPi4 diagnostics" "Docker root state" "./jeannie doctor-rpi --details" "" "" check_rpi_docker_root_state
            report_ui_check warn "RPi4 diagnostics" "Tailscale IP" "./jeannie doctor-rpi --details" "" "" check_rpi_tailscale_ip
            ;;
        debian)
            report_ui_check warn "Debian diagnostics" "Gitea runner service" "systemctl status homelab-gitea-runner.service --no-pager" "" "" check_systemd_active homelab-gitea-runner
            report_ui_check warn "Debian diagnostics" "Gitea SSH" "./jeannie doctor-gitea --details" "" "" check_gitea_ssh
            ;;
        cluster)
            report_ui_check warn "Kubernetes diagnostics" "Problem pods" "kubectl get pods -A -o wide" "" "" status_no_problem_pods
            report_ui_check warn "Kubernetes diagnostics" "Recent deployments" "kubectl get deployments -A" "" "" status_recent_deployments
            ;;
        opi5)
            if [[ "${LAB_CLUSTER_PROFILE:-}" == k3s && "${LAB_CLUSTER_RUNTIME:-}" == k3s && "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}" == "${LAB_PIMOX_HOST:-}" ]]; then
                report_ui_enqueue doctor_focus_k3s_storage_report
            fi
            ;;
    esac
}

doctor_focus() {
    local scope="${1:-}" item="" rc=0 selected area check severity evidence direct=false
    local -a flags=()
    if [[ "${1:-}" == opi5 && "${2:-}" == --repair-k3s ]]; then
        [[ $# == 2 ]] || { echo "Usage: ./jeannie doctor opi5 --repair-k3s" >&2; return 2; }
        require_debian_server "doctor opi5 --repair-k3s"
        if [[ "${JEANNIE_REMOTE_SERVER:-false}" == true ]]; then
            echo "K3s storage recovery requires the local Debian CLI." >&2
            return 2
        fi
        record_change_journal "doctor-k3s-storage" "$@"
        python3 "${REPO_ROOT}/scripts/doctor-k3s-storage.py" repair
        return $?
    fi
    case "${scope}" in
        -h|--help) doctor_focus_usage; return 0 ;;
        oci|rpi|opi5|debian|cluster) shift ;;
        all|"") doctor_focus_usage >&2; return 2 ;;
        -*) doctor_focus_usage >&2; return 2 ;;
        *) item="${scope}"; scope=cluster; direct=true; shift ;;
    esac
    while (($#)); do
        case "$1" in
            -h|--help) doctor_focus_usage; return 0 ;;
            --item)
                if (($# < 2)) || [[ -z "$2" || "$2" == --* || -n "${item}" ]]; then echo "Provide exactly one item name." >&2; return 2; fi
                item="$2"; shift 2 ;;
            --ai|--no-local-rca|--json|--details|--all) flags+=("$1"); shift ;;
            -*) echo "Unknown doctor option: $1" >&2; return 2 ;;
            *) if [[ -n "${item}" ]]; then echo "Provide exactly one item name." >&2; return 2; fi; item="$1"; shift ;;
        esac
    done
    require_debian_server "doctor"
    # These variables are consumed by the dynamically scoped report helpers.
    # shellcheck disable=SC2034
    local REPORT_UI_ONLY=all REPORT_UI_LOCAL_RCA=false REPORT_UI_PARALLEL=true REPORT_UI_STATUS_SUMMARY=false
    [[ -z "${item}" ]] || REPORT_UI_LOCAL_RCA=true
    report_ui_parse_args "${flags[@]}" || return 2
    report_ui_begin
    if [[ "${direct}" == true ]]; then
        report_ui_enqueue doctor_focus_application_lookup "${item}"
        report_ui_enqueue status_focus_compose_report "Debian Compose" local "" ""
        report_ui_enqueue status_focus_compose_report "RPi4 Compose" "${LAB_RPI_HOST:-}" "${LAB_RPI_USER:-}" "${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}"
        report_ui_enqueue status_focus_compose_report "Orange Pi Compose" "${LAB_PIMOX_HOST:-}" "${LAB_PIMOX_USER:-}" "${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}"
        report_ui_enqueue status_focus_compose_report "OCI edge Compose" "${LAB_EDGE_TAILSCALE_IP:-}" "${LAB_EDGE_USER:-}" "${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}"
    else
        status_focus_collect "${scope}"
        if [[ -z "${item}" ]]; then doctor_focus_extra "${scope}"; fi
    fi
    report_ui_finish
    if [[ "${direct}" == true ]] && awk -F '\t' '$1 == "warn" && ($2 == "Item lookup" || $3 == "Compose inventory") { found=1 } END { exit !found }' "${REPORT_UI_ROWS_FILE}"; then
        report_ui_cleanup
        echo "Some item sources are unavailable; specify a device or cluster scope to avoid an ambiguous match." >&2
        return 2
    fi
    if [[ -n "${item}" ]]; then
        if ! selected="$(python3 "${REPO_ROOT}/scripts/doctor-filter.py" "${item}" <"${REPORT_UI_ROWS_FILE}")"; then
            report_ui_cleanup
            return 2
        fi
        printf '%s\n' "${selected}" >"${REPORT_UI_ROWS_FILE}"
        REPORT_UI_FAILURES=0
        IFS=$'\t' read -r severity area check _ <<<"${selected}"
        [[ "${selected}" != fail$'\t'* ]] || REPORT_UI_FAILURES=1
        if [[ "${area}" == "Kubernetes apps" ]]; then
            # Application evidence is a separate read-only request for the selected item.
            # shellcheck disable=SC2034
            REPORT_UI_PARALLEL=false
            if evidence="$(doctor_focus_application_evidence "${check}" 2>&1)"; then
                report_ui_emit "${severity}" "Kubernetes evidence" "${check} application details" "Application state and resources" "${evidence}" "kubectl get pods -A -o wide"
            else
                report_ui_emit warn "Kubernetes evidence" "${check} application details" "Application evidence indicates a problem or could not be read" "${evidence}" "kubectl get pods -A -o wide"
            fi
        elif [[ "${area}" == *" Compose" ]]; then
            case "${area}" in
                "Debian Compose") scope=debian ;;
                "RPi4 Compose") scope=rpi ;;
                "Orange Pi Compose") scope=opi5 ;;
                "OCI edge Compose") scope=oci ;;
            esac
            # shellcheck disable=SC2034
            REPORT_UI_PARALLEL=false
            if evidence="$(doctor_focus_compose_evidence "${scope}" "${check}" 2>&1)"; then
                report_ui_emit "${severity}" "Compose evidence" "${check} container details" "Container state and restarts" "${evidence}"
            else
                report_ui_emit warn "Compose evidence" "${check} container details" "Cannot read container evidence" "${evidence}"
            fi
        fi
    fi
    ((REPORT_UI_FAILURES == 0)) || rc=1
    if [[ "${item}" == gitea-runner && "${area}" == "Kubernetes apps" && "${REPORT_UI_JSON}" != true ]]; then
        doctor_runner_report || rc=$?
        report_ui_cleanup
        return "${rc}"
    fi
    if [[ "${REPORT_UI_JSON}" == true ]]; then
        report_ui_render "Jeannie Doctor: ${scope}${item:+ / ${item}}"
    else
        python3 "${REPO_ROOT}/scripts/doctor-narrative.py" "${REPORT_UI_ROWS_FILE}" "Jeannie Doctor: ${scope}${item:+ / ${item}}"
        if truthy "${REPORT_UI_LOCAL_RCA:-false}"; then
            report_ui_local_rca "Jeannie Doctor: ${scope}${item:+ / ${item}}"
        fi
    fi
    report_ui_cleanup
    return "${rc}"
}
