#!/usr/bin/bash
# lamboot-repair — guided boot-repair tool, online + offline
#
# Canonical implementation of the toolkit's six-phase mutating-operation flow:
# diagnose → plan → show → confirm → execute → verify. Each plan step has
# a risk tier; destructive steps require extra confirmation regardless of --yes.
#
# Part of the lamboot-tools suite (SPEC-LAMBOOT-TOOLKIT-V1.md §3.1).

# shellcheck source=../lib/lamboot-toolkit-lib.sh
source "${LAMBOOT_LIB_DIR:-/usr/lib/lamboot-tools}/lamboot-toolkit-lib.sh"
# shellcheck source=../lib/lamboot-toolkit-help.sh
source "${LAMBOOT_LIB_DIR:-/usr/lib/lamboot-tools}/lamboot-toolkit-help.sh"

LAMBOOT_TOOL_NAME="lamboot-repair"
LAMBOOT_TOOL_VERSION="0.7.2"

readonly DOC_BASE="https://github.com/lamco-admin/lamboot-tools"

# Tool-specific flags
OPT_FIX_FSTAB_ONLY=0
OPT_PLAN_ONLY=0
OPT_RISK_LIMIT="moderate"  # safe | moderate | destructive
OPT_NVRAM_FILE=""          # path to OVMF VARS file for offline NVRAM ops

# Repair plan — three parallel arrays (v1.0 — could become JSON in v0.3+)
PLAN_IDS=()
PLAN_DESCS=()
PLAN_CMDS=()
PLAN_RISKS=()

# State
ESP_MOUNT=""
ESP_DEV=""
FIXES_APPLIED=0
FIXES_FAILED=0

# ── Help registry ────────────────────────────────────────────────────────

_register_subcommands() {
    register_subcommand \
        --name "repair" \
        --category "Repair" \
        --summary "Diagnose and repair boot issues (default action)" \
        --syntax "lamboot-repair [--offline DISK] [--auto] [--risk-limit LEVEL] [--fix-fstab] [--plan-only|--dry-run]" \
        --arg "--offline DISK:Operate on unmounted disk or image" \
        --arg "--auto:Execute without interactive confirmation (implies --yes)" \
        --arg "--risk-limit LEVEL:safe|moderate|destructive (default: moderate)" \
        --arg "--fix-fstab:Only run fstab-repair actions" \
        --arg "--plan-only:Equivalent to --dry-run for this tool" \
        --example "sudo lamboot-repair" \
        --example "sudo lamboot-repair --dry-run" \
        --example "sudo lamboot-repair --auto --yes" \
        --example "sudo lamboot-repair --offline /dev/pve/vm-201-disk-1" \
        --example "sudo lamboot-repair --fix-fstab --auto" \
        --notes "Six-phase flow: diagnose, plan, show, confirm, execute, verify. Each plan step has a risk tier. Destructive steps always require typed 'yes' confirmation regardless of --auto. Offline NVRAM operations deferred to v0.3+." \
        --offline-capable "true" \
        --requires-root "true" \
        --see-also "lamboot-diagnose, lamboot-esp, lamboot-migrate, lamboot-doctor" \
        --doc-url "https://github.com/lamco-admin/lamboot-tools" \
        --maturity "stable"
}

# ── Remediation helper ───────────────────────────────────────────────────

_remediation_json() {
    local id="$1" summary="$2" cmd="${3:-}"
    local doc="${DOC_BASE}/${id//.//}"
    local cmd_field="\"\""
    [[ -n "$cmd" ]] && cmd_field="\"$(json_escape "$cmd")\""
    printf '{"summary":"%s","command":%s,"doc_url":"%s"}' \
        "$(json_escape "$summary")" "$cmd_field" "$doc"
}

# ── Plan management ──────────────────────────────────────────────────────

plan_add() {
    local id="$1" desc="$2" cmd="$3" risk="${4:-safe}"
    PLAN_IDS+=("$id")
    PLAN_DESCS+=("$desc")
    PLAN_CMDS+=("$cmd")
    PLAN_RISKS+=("$risk")
}

risk_tier_ok() {
    local step_risk="$1"
    case "$OPT_RISK_LIMIT" in
        safe)
            [[ "$step_risk" == "safe" ]]
            ;;
        moderate)
            [[ "$step_risk" == "safe" ]] || [[ "$step_risk" == "moderate" ]]
            ;;
        destructive)
            true
            ;;
        *)
            die "invalid --risk-limit: $OPT_RISK_LIMIT"
            ;;
    esac
}

# ── NVRAM helpers (virt-fw-vars wrapper) ────────────────────────────────

# Inspect an OVMF VARS file via virt-fw-vars and return the formatted Boot
# variable section (BootOrder + Boot####). Returns empty string if no Boot
# entries are present. virt-fw-vars output isn't structured JSON in older
# versions, so we parse the text directly.
_nvram_dump_boot() {
    local vars_file="$1"
    [[ -f "$vars_file" ]] || [[ -b "$vars_file" ]] || return 1
    virt-fw-vars -i "$vars_file" 2>/dev/null | awk '
        /^  - name=Boot[0-9A-Fa-f]{4}$/ { in_boot=1; print; next }
        /^  - name=BootOrder$/          { in_boot=1; print; next }
        /^  - name=/                    { in_boot=0 }
        in_boot                         { print }
    '
}

# Check if any Boot#### entry references a given EFI path (case-insensitive
# match against the printable ASCII of the FilePath). Returns 0 if found,
# 1 otherwise.
_nvram_has_boot_for() {
    local vars_file="$1" efi_path="$2"
    local dump
    dump=$(_nvram_dump_boot "$vars_file") || return 1
    [[ -n "$dump" ]] || return 1
    # virt-fw-vars formats DevicePath FilePath segments like
    #   FilePath(/EFI/LamBoot/lambootx64.efi)
    # Be lenient about backslash vs forward-slash, and case.
    local needle_fwd needle_bwd
    needle_fwd=$(printf '%s' "$efi_path" | tr 'A-Z\\\\' 'a-z/')
    needle_bwd=$(printf '%s' "$efi_path" | tr 'A-Z/' 'a-z\\\\')
    printf '%s' "$dump" | tr 'A-Z' 'a-z' | grep -qE \
        "filepath\\(${needle_fwd//\//\\/}\\)|filepath\\(${needle_bwd}\\)"
}

# ── Repair actions (callable by execute_plan via eval) ─────────────────

# Append a Boot#### entry pointing at a given EFI path to the configured
# OVMF VARS file. Uses virt-fw-vars --inplace --append-boot-filepath.
# Tier: moderate. Mutates VARS file. Caller is responsible for ensuring
# the EFI binary at PATH actually exists on the matching ESP — this
# function does not verify presence (that's a separate diagnose finding).
_offline_nvram_add_boot_entry() {
    [[ -n "$OPT_NVRAM_FILE" ]] || { warn "_offline_nvram_add_boot_entry: --nvram not set"; return 1; }
    [[ -f "$OPT_NVRAM_FILE" ]] || [[ -b "$OPT_NVRAM_FILE" ]] || { warn "_offline_nvram_add_boot_entry: $OPT_NVRAM_FILE not readable"; return 1; }
    local efi_path="${1:-\\EFI\\LamBoot\\lambootx64.efi}"
    local label="${2:-LamBoot}"
    info "  appending Boot entry: $label -> $efi_path"
    if ! virt-fw-vars --inplace "$OPT_NVRAM_FILE" \
            --append-boot-filepath "$efi_path" 2>&1; then
        warn "_offline_nvram_add_boot_entry: virt-fw-vars failed"
        return 1
    fi
}

# Move a Boot#### entry to the head of BootOrder. The virt-fw-vars CLI does
# not expose this operation; we bridge to virt.firmware's Python API via
# lib/_nvram_set_first_boot.py. Used by repair.nvram.set_first when a
# LamBoot Boot entry exists in NVRAM but isn't first in BootOrder (firmware
# would auto-boot the wrong entry, e.g., the QEMU HARDDISK fallback that
# fails Access-Denied on unsigned BOOTX64.EFI).
_offline_nvram_set_first_boot() {
    [[ -n "$OPT_NVRAM_FILE" ]] || { warn "_offline_nvram_set_first_boot: --nvram not set"; return 1; }
    [[ -f "$OPT_NVRAM_FILE" ]] || [[ -b "$OPT_NVRAM_FILE" ]] || { warn "_offline_nvram_set_first_boot: $OPT_NVRAM_FILE not readable"; return 1; }
    local head_hex="${1:?head Boot#### hex required}"
    local helper="${LAMBOOT_LIB_DIR:-/usr/lib/lamboot-tools}/_nvram_set_first_boot.py"
    if [[ ! -f "$helper" ]]; then
        warn "_offline_nvram_set_first_boot: helper not present at $helper"
        return 1
    fi
    info "  reordering BootOrder: head -> Boot${head_hex^^}"
    if ! python3 "$helper" "$OPT_NVRAM_FILE" "$head_hex" 2>&1; then
        warn "_offline_nvram_set_first_boot: helper failed"
        return 1
    fi
}

# Find the Boot#### number whose loader path matches an EFI path. Echoes
# the 4-char hex on success (e.g. "0007"), empty string if not found.
_nvram_find_boot_for() {
    local vars="$1"
    local efi_path="$2"
    virt-fw-vars --input "$vars" --print 2>/dev/null \
        | awk -v p="$efi_path" '
            /^Boot[0-9A-Fa-f]{4}/ {
                # Line shape: "Boot0007            : boot entry: title=\"...\" devpath=FilePath(\\EFI\\LamBoot\\lambootx64.efi)"
                if (index($0, p) > 0) {
                    sub(/^Boot/, "", $1); print $1; exit
                }
            }'
}

# Regenerate BLS entries by chrooting into the offline rootfs and running
# kernel-install for every kernel under /usr/lib/modules/. Used when
# diagnose_offline finds zero /loader/entries/ + zero UKIs but kernels
# are installed in the rootfs. Tier: moderate. Writes to ESP /loader/entries/
# and copies kernel/initrd into the ESP per kernel-install layout=bls.
_offline_regen_bls() {
    if ! offline_chroot_has_command kernel-install; then
        warn "_offline_regen_bls: kernel-install not present in offline rootfs"
        return 1
    fi
    local kernels=()
    if [[ -d "${LAMBOOT_OFFLINE_ROOT}/usr/lib/modules" ]]; then
        local d
        for d in "${LAMBOOT_OFFLINE_ROOT}/usr/lib/modules/"*/; do
            [[ -d "$d" ]] || continue
            [[ -f "${d}vmlinuz" ]] || continue
            kernels+=("$(basename "${d%/}")")
        done
    fi
    if [[ ${#kernels[@]} -eq 0 ]]; then
        warn "_offline_regen_bls: no kernels with vmlinuz found under usr/lib/modules/"
        return 1
    fi
    info "  found ${#kernels[@]} kernel(s): ${kernels[*]}"

    # offline_chroot_run handles: remount rw, bind /dev /proc /sys, bind ESP
    # to /efi or /boot/efi, chroot in, run command. Teardown happens at
    # offline_teardown via the EXIT trap installed by offline_setup.
    local k rc=0
    for k in "${kernels[@]}"; do
        info "  kernel-install add $k"
        if ! offline_chroot_run "kernel-install add '$k' '/usr/lib/modules/$k/vmlinuz'"; then
            warn "_offline_regen_bls: kernel-install failed for $k"
            rc=1
        fi
    done
    return $rc
}

# ── Phase 1: Diagnose (online) ───────────────────────────────────────────

diagnose_online() {
    info "Phase 1 — Diagnose (online)"

    # Boot mode
    if [[ ! -d /sys/firmware/efi ]]; then
        emit_finding "repair.boot_mode.bios" "repair" "critical" "fail" \
            "System is in BIOS mode, not UEFI" \
            "Cannot manage UEFI NVRAM without UEFI boot. Repair ESP-level issues is still possible; NVRAM fixes will be skipped." \
            "{}" \
            "$(_remediation_json "repair.boot_mode.bios" \
                "Convert BIOS to UEFI" \
                "sudo lamboot-migrate to-uefi")"
    fi

    # ESP
    ESP_MOUNT=$(detect_esp 2>/dev/null || true)

    if [[ -z "$ESP_MOUNT" ]]; then
        # ESP exists but unmounted?
        local esp_part
        esp_part=$(lsblk -nrpo NAME,PARTTYPE 2>/dev/null \
            | grep -i "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" \
            | awk '{print $1}' | head -1 || true)

        if [[ -n "$esp_part" ]]; then
            emit_finding "repair.esp.unmounted" "repair_esp" "warning" "fail" \
                "ESP exists at $esp_part but is not mounted" "" \
                "{\"device\":\"$(json_escape "$esp_part")\"}" \
                "$(_remediation_json "repair.esp.unmounted" \
                    "Mount the ESP" \
                    "sudo mount $esp_part /boot/efi")"

            plan_add "repair.esp.mount" \
                "Mount ESP ($esp_part) at /boot/efi" \
                "mkdir -p /boot/efi && mount $esp_part /boot/efi" \
                "safe"
            # Try to proceed — set ESP_MOUNT assuming we'll mount it
            ESP_MOUNT="/boot/efi"
            ESP_DEV="$esp_part"
            return 0
        else
            emit_finding "repair.esp.not_found" "repair_esp" "critical" "fail" \
                "No ESP found on any disk" \
                "Cannot repair without an ESP; use lamboot-migrate to-uefi to create one." \
                "{}" \
                "$(_remediation_json "repair.esp.not_found" \
                    "Create an ESP" \
                    "sudo lamboot-migrate to-uefi")"
            return 1
        fi
    fi

    ESP_DEV=$(findmnt -n -o SOURCE "$ESP_MOUNT" 2>/dev/null || true)

    # ESP filesystem integrity
    if [[ -n "$ESP_DEV" ]] && command -v fsck.fat >/dev/null 2>&1; then
        if ! fsck.fat -n "$ESP_DEV" >/dev/null 2>&1; then
            emit_finding "repair.esp.fs_issues" "repair_esp" "warning" "fail" \
                "ESP filesystem has issues" \
                "fsck.fat -n reported problems." \
                "{\"device\":\"$(json_escape "$ESP_DEV")\"}" \
                "$(_remediation_json "repair.esp.fs_issues" \
                    "Run fsck with --auto fix" \
                    "sudo lamboot-repair --auto")"

            plan_add "repair.esp.fsck" \
                "Repair ESP filesystem" \
                "umount $ESP_MOUNT && fsck.fat -a $ESP_DEV && mount $ESP_DEV $ESP_MOUNT" \
                "moderate"
        fi
    fi

    # Fallback bootloader
    local lamboot_canonical="${ESP_MOUNT}/EFI/LamBoot/lambootx64.efi"
    if [[ ! -f "${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI" ]] && [[ ! -f "${ESP_MOUNT}/EFI/BOOT/bootx64.efi" ]]; then
        local fb_src=""
        for candidate in \
            "$lamboot_canonical" \
            "${ESP_MOUNT}"/EFI/*/shimx64.efi \
            "${ESP_MOUNT}"/EFI/*/grubx64.efi \
            "${ESP_MOUNT}/EFI/systemd/systemd-bootx64.efi"; do
            if [[ -f "$candidate" ]]; then
                fb_src="$candidate"
                break
            fi
        done

        if [[ -n "$fb_src" ]]; then
            emit_finding "repair.fallback.missing" "repair_fallback" "warning" "fail" \
                "Fallback loader EFI/BOOT/BOOTX64.EFI missing" \
                "Will copy from $(basename "$fb_src")." \
                "{\"source\":\"$(json_escape "$fb_src")\"}" \
                "$(_remediation_json "repair.fallback.missing" \
                    "Install fallback from existing bootloader" \
                    "sudo lamboot-repair --auto")"

            plan_add "repair.fallback.install" \
                "Install fallback bootloader from $(basename "$fb_src")" \
                "mkdir -p ${ESP_MOUNT}/EFI/BOOT && cp '$fb_src' '${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI'" \
                "safe"
        else
            emit_finding "repair.fallback.no_source" "repair_fallback" "warning" "skip" \
                "Fallback loader missing; no existing bootloader to copy from" \
                "Install a bootloader (LamBoot / GRUB / sd-boot / rEFInd) first." "{}" '{}'
        fi
    elif [[ -f "${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI" ]] && [[ -f "$lamboot_canonical" ]]; then
        # BOOTX64.EFI exists AND LamBoot is installed. Check whether they're
        # the same binary — if not, the firmware HARDDISK fallback path will
        # try BOOTX64.EFI which might be unsigned (BOOTX64=systemd-boot,
        # grub, etc.) and Access-Denied under SB. The fix that worked on
        # VM 123: replace BOOTX64.EFI with the signed LamBoot binary so the
        # firmware fallback always succeeds even when no Boot#### entry
        # explicitly points at LamBoot. See VM-123-RECOVERY-HANDOVER §4.
        local bootx_hash lamboot_hash
        bootx_hash=$(sha256sum "${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI" 2>/dev/null | cut -d' ' -f1 || true)
        lamboot_hash=$(sha256sum "$lamboot_canonical" 2>/dev/null | cut -d' ' -f1 || true)
        if [[ -n "$bootx_hash" ]] && [[ -n "$lamboot_hash" ]] && [[ "$bootx_hash" != "$lamboot_hash" ]]; then
            emit_finding "repair.fallback.foreign" "repair_fallback" "warning" "warn" \
                "EFI/BOOT/BOOTX64.EFI is not LamBoot" \
                "Firmware HARDDISK fallback will try this binary; under Secure Boot it may be Access-Denied if not signed by a cert in db. Replace with LamBoot's signed binary for belt-and-suspenders boot." \
                "{\"bootx64_sha256\":\"$(json_escape "$bootx_hash")\",\"lamboot_sha256\":\"$(json_escape "$lamboot_hash")\"}" \
                "$(_remediation_json "repair.fallback.foreign" \
                    "Replace BOOTX64.EFI with LamBoot's signed binary" \
                    "sudo lamboot-repair --auto")"

            plan_add "repair.fallback.replace_with_lamboot" \
                "Replace EFI/BOOT/BOOTX64.EFI with LamBoot's signed binary (orig saved as .pre-lamboot)" \
                "mv -f '${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI' '${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI.pre-lamboot' && cp '$lamboot_canonical' '${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI'" \
                "moderate"
        fi
    fi

    # UEFI boot entries
    if [[ -d /sys/firmware/efi ]] && command -v efibootmgr >/dev/null 2>&1; then
        local entries
        entries=$(efibootmgr 2>/dev/null | grep -cE '^Boot[0-9A-Fa-f]{4}' || true)
        [[ -z "$entries" ]] && entries=0

        if [[ "$entries" -eq 0 ]] && [[ -f "${ESP_MOUNT}/EFI/LamBoot/lambootx64.efi" ]]; then
            local disk partnum
            disk=$(lsblk -nro PKNAME "$ESP_DEV" 2>/dev/null | head -1 || true)
            partnum=$(lsblk -nro PARTN "$ESP_DEV" 2>/dev/null | head -1 || true)

            if [[ -n "$disk" ]] && [[ -n "$partnum" ]]; then
                emit_finding "repair.nvram.no_entries" "repair_nvram" "error" "fail" \
                    "No UEFI boot entries in NVRAM" \
                    "Can create a LamBoot entry on /dev/$disk partition $partnum." \
                    "{\"entries\":0,\"disk\":\"/dev/$disk\",\"part\":${partnum}}" \
                    "$(_remediation_json "repair.nvram.no_entries" \
                        "Create a LamBoot NVRAM entry" \
                        "sudo lamboot-repair --auto")"

                plan_add "repair.nvram.create_lamboot" \
                    "Create LamBoot UEFI boot entry" \
                    "efibootmgr --create --disk /dev/$disk --part $partnum --loader '\\EFI\\LamBoot\\lambootx64.efi' --label LamBoot --quiet" \
                    "safe"
            fi
        else
            # Check BootOrder
            local bootorder
            bootorder=$(efibootmgr 2>/dev/null | grep '^BootOrder:' | cut -d: -f2 | tr -d ' ' || true)
            if [[ -z "$bootorder" ]] && [[ "$entries" -gt 0 ]]; then
                local discovered
                discovered=$(efibootmgr 2>/dev/null | grep -oE '^Boot[0-9A-Fa-f]{4}' | sed 's/Boot//' | tr '\n' ',' | sed 's/,$//')
                if [[ -n "$discovered" ]]; then
                    emit_finding "repair.nvram.bootorder_unset" "repair_nvram" "warning" "fail" \
                        "BootOrder variable not set" \
                        "Discovered entries: $discovered." \
                        "{\"discovered\":\"$(json_escape "$discovered")\"}" \
                        "$(_remediation_json "repair.nvram.bootorder_unset" \
                            "Set BootOrder" \
                            "sudo lamboot-repair --auto")"
                    plan_add "repair.nvram.set_bootorder" \
                        "Set BootOrder to $discovered" \
                        "efibootmgr --bootorder $discovered --quiet" \
                        "safe"
                fi
            fi
        fi
    fi

    # fstab ESP entry
    if ! grep -q "$ESP_MOUNT" /etc/fstab 2>/dev/null && [[ -n "$ESP_DEV" ]]; then
        local uuid
        uuid=$(blkid -s UUID -o value "$ESP_DEV" 2>/dev/null || true)
        if [[ -n "$uuid" ]]; then
            emit_finding "repair.fstab.missing_esp" "repair_fstab" "warning" "fail" \
                "ESP entry missing from /etc/fstab" \
                "$ESP_MOUNT will not mount automatically on boot." \
                "{\"esp_mount\":\"$ESP_MOUNT\",\"uuid\":\"$uuid\"}" \
                "$(_remediation_json "repair.fstab.missing_esp" \
                    "Add ESP entry to fstab" \
                    "sudo lamboot-repair --fix-fstab --auto")"
            plan_add "repair.fstab.add_esp" \
                "Add ESP to /etc/fstab" \
                "echo 'UUID=$uuid $ESP_MOUNT vfat umask=0077,shortname=winnt 0 1' >> /etc/fstab" \
                "safe"
        fi
    fi

    # LamBoot health state — only actionable if CrashLoop or stuck Booting
    local state_var="/sys/firmware/efi/efivars/LamBootState-4c414d42-4f4f-5400-0000-000000000001"
    if [[ -r "$state_var" ]]; then
        local state
        state=$(od -An -t u1 -j4 -N1 "$state_var" 2>/dev/null | tr -d ' ' || printf '0')
        if [[ "$state" == "3" ]]; then
            emit_finding "repair.lamboot.crash_loop" "repair_lamboot" "critical" "fail" \
                "LamBoot in CrashLoop state" \
                "Boot counter exceeded threshold; LamBoot is refusing to try the last entry." \
                "{\"state\":3}" \
                "$(_remediation_json "repair.lamboot.crash_loop" \
                    "Reset crash counter + state" \
                    "sudo lamboot-repair --auto")"
            plan_add "repair.lamboot.reset_crash" \
                "Reset LamBoot crash counter + state" \
                "chattr -i '${state_var}' 2>/dev/null; printf '\\x07\\x00\\x00\\x00\\x02' > '${state_var}'" \
                "safe"
        elif [[ "$state" == "1" ]]; then
            emit_finding "repair.lamboot.stuck_booting" "repair_lamboot" "warning" "warn" \
                "LamBoot stuck in Booting state" \
                "Previous boot may not have reached mark-success." \
                "{\"state\":1}" \
                "$(_remediation_json "repair.lamboot.stuck_booting" \
                    "Reset state to BootedOK" \
                    "sudo lamboot-repair --auto")"
            plan_add "repair.lamboot.reset_state" \
                "Reset LamBoot state to BootedOK" \
                "chattr -i '${state_var}' 2>/dev/null; printf '\\x07\\x00\\x00\\x00\\x02' > '${state_var}'" \
                "safe"
        fi
    fi

    # mark-success service
    if [[ -f /usr/lib/systemd/system/lamboot-mark-success.service ]]; then
        if command -v systemctl >/dev/null 2>&1 && ! systemctl is-enabled lamboot-mark-success.service >/dev/null 2>&1; then
            emit_finding "repair.lamboot.mark_success_disabled" "repair_lamboot" "warning" "fail" \
                "lamboot-mark-success.service not enabled" \
                "Crash-loop recovery won't work until the service runs on boot." "{}" \
                "$(_remediation_json "repair.lamboot.mark_success_disabled" \
                    "Enable the service" \
                    "sudo systemctl enable lamboot-mark-success.service")"
            plan_add "repair.lamboot.enable_mark_success" \
                "Enable lamboot-mark-success.service" \
                "systemctl enable lamboot-mark-success.service" \
                "safe"
        fi
    fi
}

# ── Phase 1 (offline) ────────────────────────────────────────────────────

diagnose_offline() {
    info "Phase 1 — Diagnose (offline)"

    if [[ $LAMBOOT_OFFLINE_ACTIVE -ne 1 ]]; then
        die "offline mode not active (internal error)"
    fi

    if [[ -z "$LAMBOOT_OFFLINE_ESP" ]]; then
        emit_finding "repair.offline.no_esp" "repair_esp" "critical" "fail" \
            "No ESP detected on offline disk" \
            "Disk layout may be non-UEFI or corrupted." \
            "{\"disk\":\"$(json_escape "$LAMBOOT_OFFLINE_LOOP_DEV")\"}" \
            "$(_remediation_json "repair.offline.no_esp" \
                "Inspect with lamboot-esp inventory" \
                "sudo lamboot-esp inventory --offline <disk>")"
        return 1
    fi

    ESP_MOUNT="$LAMBOOT_OFFLINE_ESP"

    # Fallback loader check (offline, read-only mount — can identify but can't always repair)
    if [[ ! -f "${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI" ]] && [[ ! -f "${ESP_MOUNT}/EFI/BOOT/bootx64.efi" ]]; then
        emit_finding "repair.offline.fallback_missing" "repair_fallback" "warning" "fail" \
            "Offline ESP missing fallback loader" \
            "No \\EFI\\BOOT\\BOOTX64.EFI present. Firmware will not boot from removable media without an explicit NVRAM entry." "{}" \
            "$(_remediation_json "repair.offline.fallback_missing" \
                "Reinstall bootloader (LamBoot or distro)" \
                "sudo lamboot-install --signed (after booting recovery media)")"
    fi

    # Detect partial-uninstall residue: /EFI/LamBoot/ subtree exists (drivers/
    # or reports/ dir) but no lambootx64.efi. Caused by old lamboot-install
    # --remove paths whose final rmdir loop silently failed on non-empty dirs
    # (leftover LICENSE-GPL-2.0.txt + runtime logs from reports/). Fixed in
    # lamboot-install commit 75abd06; this finding flags ESPs that still carry
    # the residue from a pre-fix --remove.
    local lb_dir="${ESP_MOUNT}/EFI/LamBoot"
    if [[ -d "$lb_dir" ]] && [[ ! -f "${lb_dir}/lambootx64.efi" ]] && [[ ! -f "${lb_dir}/lambootx64-signed.efi" ]]; then
        local has_residue=0
        local residue_items=()
        [[ -d "${lb_dir}/drivers" ]]  && { has_residue=1; residue_items+=("drivers/"); }
        [[ -d "${lb_dir}/reports" ]]  && { has_residue=1; residue_items+=("reports/"); }
        [[ -d "${lb_dir}/modules" ]]  && { has_residue=1; residue_items+=("modules/"); }
        if (( has_residue )); then
            emit_finding "repair.offline.lamboot_residue" "repair_lamboot" "warning" "fail" \
                "LamBoot install tree present but binary missing" \
                "Found ${residue_items[*]} under \\EFI\\LamBoot\\ with no lambootx64.efi. Indicates a partial --remove from before lamboot-install commit 75abd06, or an interrupted install." \
                "{\"residue\":[$(printf '"%s",' "${residue_items[@]}" | sed 's/,$//')]}" \
                "$(_remediation_json "repair.offline.lamboot_residue" \
                    "Reinstall or fully clean up" \
                    "sudo lamboot-install --signed   (or)   sudo lamboot-install --remove --force")"
        fi
    fi

    # Detect "BLS bootloader advertised but no entries available". A systemd-
    # boot install (or LamBoot itself) reads /loader/entries/*.conf to present
    # boot options. If the directory exists but is empty, AND there are no UKIs
    # under /EFI/Linux/, the bootloader will display "No boot entries found"
    # and the user has no way forward.
    local entries_dir="${ESP_MOUNT}/loader/entries"
    local linux_dir="${ESP_MOUNT}/EFI/Linux"
    local has_systemd_boot=0
    local has_lamboot=0
    [[ -f "${ESP_MOUNT}/EFI/systemd/systemd-bootx64.efi" ]] && has_systemd_boot=1
    [[ -f "${ESP_MOUNT}/EFI/LamBoot/lambootx64.efi" ]] || [[ -f "${ESP_MOUNT}/EFI/LamBoot/lambootx64-signed.efi" ]] && has_lamboot=1

    if (( has_systemd_boot )) || (( has_lamboot )); then
        local entry_count=0 uki_count=0
        if [[ -d "$entries_dir" ]]; then
            entry_count=$(find "$entries_dir" -maxdepth 1 -name '*.conf' 2>/dev/null | wc -l | tr -d ' ')
        fi
        if [[ -d "$linux_dir" ]]; then
            uki_count=$(find "$linux_dir" -maxdepth 1 -name '*.efi' 2>/dev/null | wc -l | tr -d ' ')
        fi

        if [[ "$entry_count" -eq 0 ]] && [[ "$uki_count" -eq 0 ]]; then
            local bootloaders=""
            (( has_systemd_boot )) && bootloaders="systemd-boot"
            (( has_lamboot ))      && bootloaders="${bootloaders:+$bootloaders, }LamBoot"

            # If the offline rootfs has kernel-install, we can auto-fix this:
            # remount rw, bind /dev /proc /sys, chroot in, run kernel-install
            # add-all. Plan this as a moderate-risk step. Without a rootfs or
            # without kernel-install, fall back to advice-only.
            local can_autofix=0
            if [[ -n "$LAMBOOT_OFFLINE_ROOT" ]] && offline_chroot_has_command kernel-install; then
                can_autofix=1
            fi

            if (( can_autofix )); then
                emit_finding "repair.offline.no_boot_entries" "repair_entries" "critical" "fail" \
                    "Bootloader installed but no boot entries present" \
                    "$bootloaders is on the ESP, but /loader/entries/ has zero .conf files and /EFI/Linux/ has zero UKIs. Will be auto-repaired via kernel-install in offline chroot." \
                    "{\"bootloaders\":\"$(json_escape "$bootloaders")\",\"entries\":${entry_count},\"ukis\":${uki_count},\"autofix\":\"chroot_kernel_install\"}" \
                    "$(_remediation_json "repair.offline.no_boot_entries" \
                        "Regenerate BLS entries via kernel-install in chroot" \
                        "sudo lamboot-repair --offline <disk> --apply")"

                plan_add "repair.offline.regen_bls" \
                    "Regenerate BLS entries via kernel-install in offline chroot" \
                    "_offline_regen_bls" \
                    "moderate"
            else
                local why="no rootfs detected on disk"
                [[ -n "$LAMBOOT_OFFLINE_ROOT" ]] && why="kernel-install not present in offline rootfs"
                emit_finding "repair.offline.no_boot_entries" "repair_entries" "critical" "fail" \
                    "Bootloader installed but no boot entries present" \
                    "$bootloaders is on the ESP, but /loader/entries/ has zero .conf files and /EFI/Linux/ has zero UKIs. Auto-repair unavailable: $why. Boot the OS via rescue media and run kernel-install or reinstall the kernels." \
                    "{\"bootloaders\":\"$(json_escape "$bootloaders")\",\"entries\":${entry_count},\"ukis\":${uki_count},\"autofix\":null,\"reason\":\"$(json_escape "$why")\"}" \
                    "$(_remediation_json "repair.offline.no_boot_entries" \
                        "Boot rescue media and regenerate" \
                        "sudo kernel-install add-all   (run from inside the OS)")"
            fi
        fi
    fi

    diagnose_offline_nvram
}

# Inspect an OVMF VARS file (when --nvram FILE was provided) and emit findings
# about Boot#### entries. Auto-fix: append a Boot entry pointing at LamBoot
# when one is missing AND lambootx64.efi is actually present on the ESP.
diagnose_offline_nvram() {
    if [[ -z "$OPT_NVRAM_FILE" ]]; then
        emit_finding "repair.offline.nvram_skipped" "repair_nvram" "info" "skip" \
            "NVRAM not inspected (no --nvram FILE provided)" \
            "Pass --nvram /path/to/OVMF_VARS.fd to inspect or repair Boot entries." \
            "{}" '{}'
        return 0
    fi
    # Accept regular files (raw VARS dumps) AND block devices (Proxmox stores
    # OVMF VARS as small ZFS zvols accessed via /dev/zvol/POOL/vm-NN-disk-X).
    if [[ ! -f "$OPT_NVRAM_FILE" ]] && [[ ! -b "$OPT_NVRAM_FILE" ]]; then
        emit_finding "repair.offline.nvram_missing" "repair_nvram" "error" "fail" \
            "NVRAM path not readable" \
            "$OPT_NVRAM_FILE is neither a regular file nor a block device." \
            "{\"path\":\"$(json_escape "$OPT_NVRAM_FILE")\"}" '{}'
        return 1
    fi
    if ! command -v virt-fw-vars >/dev/null 2>&1; then
        emit_finding "repair.offline.nvram_no_tool" "repair_nvram" "error" "fail" \
            "virt-fw-vars not available" \
            "Install python3-virt-firmware (Debian/Ubuntu) or pip install virt-firmware." \
            "{}" \
            "$(_remediation_json "repair.offline.nvram_no_tool" \
                "Install virt-firmware" \
                "sudo apt install python3-virt-firmware")"
        return 1
    fi

    local boot_dump
    boot_dump=$(_nvram_dump_boot "$OPT_NVRAM_FILE")
    local entry_count
    entry_count=$(printf '%s\n' "$boot_dump" | grep -c '^  - name=Boot[0-9A-Fa-f]\{4\}$' || true)
    emit_finding "repair.nvram.entry_count" "repair_nvram" "info" "pass" \
        "$entry_count Boot#### entries in NVRAM" "" \
        "{\"count\":${entry_count},\"file\":\"$(json_escape "$OPT_NVRAM_FILE")\"}" '{}'

    # Decide whether to plan a LamBoot Boot#### append: either NVRAM has zero
    # entries (efidisk regenerated) or no entry references the LamBoot path.
    local lamboot_efi="\\EFI\\LamBoot\\lambootx64.efi"
    local has_lamboot_entry=0
    if _nvram_has_boot_for "$OPT_NVRAM_FILE" "$lamboot_efi"; then
        has_lamboot_entry=1
    fi

    # Only auto-fix when the binary actually exists on the offline ESP — adding
    # a Boot entry that points at a missing file creates a dead entry that
    # firmware will skip and could mask other problems.
    local binary_present=0
    if [[ -f "${ESP_MOUNT}/EFI/LamBoot/lambootx64.efi" ]] || \
       [[ -f "${ESP_MOUNT}/EFI/LamBoot/lambootx64-signed.efi" ]]; then
        binary_present=1
    fi

    if (( has_lamboot_entry )); then
        emit_finding "repair.nvram.lamboot_entry" "repair_nvram" "info" "pass" \
            "NVRAM has a Boot entry referencing LamBoot" "" \
            "{\"path\":\"$(json_escape "$lamboot_efi")\"}" '{}'

        # LamBoot Boot#### exists; check whether it's at the head of BootOrder.
        # If not, firmware auto-boot will pick another entry (typically a
        # generic HARDDISK that falls back to \EFI\BOOT\BOOTX64.EFI which
        # may be unsigned and Access-Denied under SB) — visible at the
        # firmware Boot Manager prompt rather than booting the OS.
        local lamboot_idx bootorder_first
        lamboot_idx=$(_nvram_find_boot_for "$OPT_NVRAM_FILE" "$lamboot_efi" || true)
        bootorder_first=$(virt-fw-vars --input "$OPT_NVRAM_FILE" --print 2>/dev/null \
            | awk -F': boot order: ' '/^BootOrder/ {print $2; exit}' \
            | awk -F',' '{gsub(/[[:space:]]/,"",$1); print $1}')
        if [[ -n "$lamboot_idx" ]] && [[ -n "$bootorder_first" ]] \
           && [[ "${bootorder_first^^}" != "${lamboot_idx^^}" ]]; then
            emit_finding "repair.nvram.lamboot_not_first" "repair_nvram" "warning" "fail" \
                "LamBoot Boot entry exists but isn't first in BootOrder" \
                "BootOrder head is Boot${bootorder_first^^}; LamBoot is Boot${lamboot_idx^^}. Firmware auto-boot will pick the head, not LamBoot. Reorder needed." \
                "{\"head\":\"${bootorder_first^^}\",\"lamboot\":\"${lamboot_idx^^}\",\"autofix\":\"set_first\"}" \
                "$(_remediation_json "repair.nvram.lamboot_not_first" \
                    "Move LamBoot to head of BootOrder" \
                    "sudo lamboot-repair --offline DISK --nvram VARS --apply")"
            plan_add "repair.nvram.set_first" \
                "Move Boot${lamboot_idx^^} (LamBoot) to head of BootOrder" \
                "_offline_nvram_set_first_boot '$lamboot_idx'" \
                "moderate"
        fi
    elif (( binary_present )); then
        emit_finding "repair.nvram.lamboot_entry" "repair_nvram" "warning" "fail" \
            "NVRAM has no Boot entry for LamBoot" \
            "lambootx64.efi exists on the ESP but no Boot#### entry references it; firmware will fall back to \\EFI\\BOOT\\BOOTX64.EFI or fail to boot." \
            "{\"path\":\"$(json_escape "$lamboot_efi")\",\"binary_present\":true,\"autofix\":\"append_boot_filepath\"}" \
            "$(_remediation_json "repair.nvram.lamboot_entry" \
                "Append a LamBoot Boot entry to NVRAM" \
                "sudo lamboot-repair --offline DISK --nvram VARS --apply")"
        plan_add "repair.nvram.add_lamboot_entry" \
            "Append Boot#### entry pointing at \\EFI\\LamBoot\\lambootx64.efi" \
            "_offline_nvram_add_boot_entry '\\EFI\\LamBoot\\lambootx64.efi' 'LamBoot'" \
            "moderate"
    else
        emit_finding "repair.nvram.lamboot_entry" "repair_nvram" "info" "skip" \
            "NVRAM has no LamBoot entry, but binary is also missing" \
            "Reinstall LamBoot to the ESP first, then re-run with --nvram to add the Boot entry." \
            "{\"path\":\"$(json_escape "$lamboot_efi")\",\"binary_present\":false}" \
            "$(_remediation_json "repair.nvram.lamboot_entry" \
                "Reinstall LamBoot first" \
                "sudo lamboot-install --signed   (then re-run lamboot-repair --nvram)")"
    fi
}

# ── Phase 2: Show plan ───────────────────────────────────────────────────

show_plan() {
    info "Phase 2 — Plan"

    local count=${#PLAN_IDS[@]}
    if [[ $count -eq 0 ]]; then
        info "No repair actions needed."
        return 0
    fi

    printf '\nProposed repair plan (%d step%s):\n\n' "$count" "$([[ $count -ne 1 ]] && printf 's' || true)" >&2

    local i
    for i in "${!PLAN_IDS[@]}"; do
        local risk_tag=""
        case "${PLAN_RISKS[$i]}" in
            safe)        risk_tag="[safe]" ;;
            moderate)    risk_tag="[MODERATE]" ;;
            destructive) risk_tag="[DESTRUCTIVE]" ;;
        esac
        printf '  %d. %s %s\n' "$((i + 1))" "${PLAN_DESCS[$i]}" "$risk_tag" >&2
        if [[ $LAMBOOT_VERBOSE -eq 1 ]]; then
            printf '       cmd: %s\n' "${PLAN_CMDS[$i]}" >&2
        fi
    done
    printf '\n' >&2
}

# ── Phase 3: Confirm ─────────────────────────────────────────────────────

phase_confirm() {
    local count=${#PLAN_IDS[@]}
    [[ $count -eq 0 ]] && return 0

    # Destructive steps always require typed yes, regardless of --auto/--yes
    local has_destructive=0
    for risk in "${PLAN_RISKS[@]}"; do
        [[ "$risk" == "destructive" ]] && has_destructive=1
    done

    if [[ $has_destructive -eq 1 ]]; then
        info "Plan contains destructive steps — typed confirmation required"
        if ! confirm "PROCEED WITH DESTRUCTIVE REPAIRS" "yes"; then
            return 1
        fi
    elif [[ $LAMBOOT_AUTO -eq 1 ]] || [[ $LAMBOOT_YES -eq 1 ]]; then
        verbose "auto-confirmed plan"
        return 0
    else
        if ! confirm "PROCEED WITH REPAIRS" "yes"; then
            return 1
        fi
    fi
    return 0
}

# ── Phase 4: Execute ─────────────────────────────────────────────────────

execute_plan() {
    info "Phase 4 — Execute"

    local count=${#PLAN_IDS[@]}
    [[ $count -eq 0 ]] && return 0

    local i
    for i in "${!PLAN_IDS[@]}"; do
        local id="${PLAN_IDS[$i]}"
        local desc="${PLAN_DESCS[$i]}"
        local cmd="${PLAN_CMDS[$i]}"
        local risk="${PLAN_RISKS[$i]}"

        if ! risk_tier_ok "$risk"; then
            warn "skipping $id (risk=$risk exceeds --risk-limit=$OPT_RISK_LIMIT)"
            record_action "$id" "$desc" "skipped" "false" \
                "{\"reason\":\"risk_limit\"}" "null"
            continue
        fi

        # --fix-fstab filter
        if [[ $OPT_FIX_FSTAB_ONLY -eq 1 ]] && [[ "$id" != *fstab* ]]; then
            verbose "skipping $id (not an fstab action, --fix-fstab set)"
            continue
        fi

        info "  [$((i + 1))/$count] $desc"

        if [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
            printf 'DRY-RUN: would exec: %s\n' "$cmd" >&2
            record_action "$id" "$desc" "ok" "true" \
                "{\"risk\":\"$risk\",\"dry_run\":true}" "null"
            continue
        fi

        if eval "$cmd" 2>&1; then
            success "applied: $desc"
            record_action "$id" "$desc" "ok" "true" \
                "{\"risk\":\"$risk\"}" "null"
            FIXES_APPLIED=$((FIXES_APPLIED + 1))
        else
            warn "failed: $desc"
            record_action "$id" "$desc" "fail" "true" \
                "{\"risk\":\"$risk\"}" "null"
            FIXES_FAILED=$((FIXES_FAILED + 1))
        fi
    done
}

# ── Phase 5: Verify ──────────────────────────────────────────────────────

verify_repairs() {
    info "Phase 5 — Verify"

    [[ $FIXES_APPLIED -eq 0 ]] && [[ $LAMBOOT_DRY_RUN -eq 0 ]] && return 0

    local pass=0 fail=0

    # ESP mounted
    if [[ $LAMBOOT_OFFLINE_ACTIVE -eq 0 ]]; then
        local current_esp
        current_esp=$(detect_esp 2>/dev/null || true)
        if [[ -n "$current_esp" ]]; then
            pass=$((pass + 1))
            verbose "verify: ESP mounted at $current_esp"
        fi
    fi

    # Fallback loader
    if [[ -n "$ESP_MOUNT" ]]; then
        if [[ -f "${ESP_MOUNT}/EFI/BOOT/BOOTX64.EFI" ]] || [[ -f "${ESP_MOUNT}/EFI/BOOT/bootx64.efi" ]]; then
            pass=$((pass + 1))
            verbose "verify: fallback loader present"
        fi
    fi

    # Boot entries
    if [[ $LAMBOOT_OFFLINE_ACTIVE -eq 0 ]] && [[ -d /sys/firmware/efi ]] && command -v efibootmgr >/dev/null 2>&1; then
        local n
        n=$(efibootmgr 2>/dev/null | grep -cE '^Boot[0-9A-Fa-f]{4}' || true)
        [[ -z "$n" ]] && n=0
        if [[ "$n" -gt 0 ]]; then
            pass=$((pass + 1))
            verbose "verify: $n UEFI boot entries in NVRAM"
        fi
    fi

    # LamBoot state
    local state_var="/sys/firmware/efi/efivars/LamBootState-4c414d42-4f4f-5400-0000-000000000001"
    if [[ -r "$state_var" ]]; then
        local state
        state=$(od -An -t u1 -j4 -N1 "$state_var" 2>/dev/null | tr -d ' ' || printf '0')
        if [[ "$state" == "2" ]]; then
            pass=$((pass + 1))
            verbose "verify: LamBoot state BootedOK"
        fi
    fi

    emit_finding "repair.verify.summary" "repair" "info" "pass" \
        "Verification: $pass checks passed, $fail failed" "" \
        "{\"passed\":$pass,\"failed\":$fail,\"applied\":${FIXES_APPLIED},\"plan_failed\":${FIXES_FAILED}}" \
        '{}'
}

# ── Main flow ────────────────────────────────────────────────────────────

do_repair() {
    require_root

    if [[ $LAMBOOT_OFFLINE_ACTIVE -eq 1 ]]; then
        diagnose_offline || true
    else
        diagnose_online || true
    fi

    show_plan

    local count=${#PLAN_IDS[@]}
    if [[ $count -eq 0 ]]; then
        info "No repair actions needed — system appears healthy."
        emit_json "$EXIT_NOOP"
        exit "$EXIT_NOOP"
    fi

    # Plan-only / dry-run: show and exit without executing
    if [[ $OPT_PLAN_ONLY -eq 1 ]] || [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
        info "Dry-run: plan shown, not executed"
        execute_plan  # Dry-run branch inside records would-be actions
        emit_json "$EXIT_OK"
        exit "$EXIT_OK"
    fi

    # Confirm (phase 3)
    if ! phase_confirm; then
        info "Aborted by user"
        emit_json "$EXIT_ABORT"
        exit "$EXIT_ABORT"
    fi

    # Execute (phase 4)
    execute_plan

    # Verify (phase 5)
    verify_repairs

    local exit_code="$EXIT_OK"
    if [[ $FIXES_FAILED -gt 0 ]] && [[ $FIXES_APPLIED -gt 0 ]]; then
        exit_code="$EXIT_PARTIAL"
    elif [[ $FIXES_FAILED -gt 0 ]]; then
        exit_code="$EXIT_ERROR"
    fi

    success "Applied $FIXES_APPLIED of $count repair action(s); $FIXES_FAILED failed"
    emit_json "$exit_code"
    exit "$exit_code"
}

# ── CLI ──────────────────────────────────────────────────────────────────

parse_args() {
    while [[ $# -gt 0 ]]; do
        parse_common_flag "$1"
        local rc=$?
        case $rc in
            1) shift; continue ;;
            2) _register_subcommands; dispatch_help; exit 0 ;;
            3) printf 'lamboot-repair %s (lamboot-tools %s)\n' \
                "$LAMBOOT_TOOL_VERSION" "$LAMBOOT_TOOLKIT_VERSION"; exit 0 ;;
            4) printf '{"$schema":"https://github.com/lamco-admin/lamboot-tools"}\n'; exit 0 ;;
            5) shift
               [[ $# -gt 0 ]] || die "--offline requires a disk path"
               offline_setup "$1"
               shift
               continue ;;
            0) ;;
        esac

        case "$1" in
            --fix-fstab)    OPT_FIX_FSTAB_ONLY=1; shift ;;
            --plan-only)    OPT_PLAN_ONLY=1; LAMBOOT_DRY_RUN=1; shift ;;
            --risk-limit)   OPT_RISK_LIMIT="${2:-moderate}"; shift 2 ;;
            --nvram)        [[ -n "${2:-}" ]] || die "--nvram requires a path"
                            OPT_NVRAM_FILE="$2"; shift 2 ;;
            help)           _register_subcommands
                            if [[ -n "${2:-}" ]]; then
                                dispatch_help "$2"
                            else
                                dispatch_help
                            fi
                            exit 0 ;;
            repair)         shift ;;
            -*)             die "unknown option: $1" ;;
            *)              die "unknown argument: $1" ;;
        esac
    done
}

main() {
    parse_args "$@"
    do_repair
}

main "$@"
