#!/usr/bin/env bash

REPORT_UI_ONLY="${REPORT_UI_ONLY:-problems}"
REPORT_UI_DETAILS=false
REPORT_UI_JSON=false
REPORT_UI_LOCAL_RCA="${REPORT_UI_LOCAL_RCA:-false}"
# shellcheck disable=SC2034
REPORT_UI_VERBOSE=false
REPORT_UI_ROWS_FILE=""
REPORT_UI_WORK_DIR=""
REPORT_UI_FAILURES=0

report_ui_usage_flags() {
    cat <<'EOF'
Report UI flags:
  --all             Show ok, informational, skip, warning, and failing items.
  --details         Show the compact report plus detail fields.
  --json            Print structured JSON.
  --ai              Ask the local AI gateway for an unverified explanation.
  --no-local-rca    Disable the AI explanation, including when enabled by environment.
  --verbose         Use the older full diagnostic output when supported.
EOF
}

report_ui_parse_args() {
    REPORT_UI_ONLY="${REPORT_UI_ONLY:-problems}"
    REPORT_UI_DETAILS=false
    REPORT_UI_JSON=false
    REPORT_UI_VERBOSE=false
    while (($# > 0)); do
        case "$1" in
            --all)
                REPORT_UI_ONLY="all"
                shift
                ;;
            --details)
                REPORT_UI_DETAILS=true
                shift
                ;;
            --json)
                REPORT_UI_JSON=true
                shift
                ;;
            --ai)
                REPORT_UI_LOCAL_RCA=true
                shift
                ;;
            --no-local-rca)
                REPORT_UI_LOCAL_RCA=false
                shift
                ;;
            --verbose)
                # shellcheck disable=SC2034
                REPORT_UI_VERBOSE=true
                shift
                ;;
            -h|--help)
                report_ui_usage_flags
                return 2
                ;;
            *)
                echo "unknown report option: $1" >&2
                return 1
                ;;
        esac
    done
}

report_ui_begin() {
    REPORT_UI_ROWS_FILE="$(mktemp "${TMPDIR:-/tmp}/jeannie-report-rows.XXXXXX")"
    REPORT_UI_WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/jeannie-report-work.XXXXXX")"
    REPORT_UI_FAILURES=0
    REPORT_UI_JOB_COUNT=0
    REPORT_UI_JOB_WAITED=0
    REPORT_UI_JOB_PIDS=()
    REPORT_UI_STARTED_SECONDS=${SECONDS}
    export REPORT_UI_WORK_DIR
}

report_ui_cleanup() {
    if [[ -n "${REPORT_UI_ROWS_FILE:-}" && -f "${REPORT_UI_ROWS_FILE}" ]]; then
        rm -f "${REPORT_UI_ROWS_FILE}"
    fi
    if [[ -n "${REPORT_UI_WORK_DIR:-}" && -d "${REPORT_UI_WORK_DIR}" ]]; then
        rm -rf "${REPORT_UI_WORK_DIR}"
    fi
    REPORT_UI_ROWS_FILE=""
    REPORT_UI_WORK_DIR=""
}

# Reuse only explicitly read-only probes, within this report. The lock avoids
# duplicate network checks when independent jobs request the same probe.
report_ui_cached_probe() {
    if [[ -z "${REPORT_UI_WORK_DIR:-}" ]] || ! command -v flock >/dev/null 2>&1; then
        "$@"
        return $?
    fi
    local key lock_fd rc
    key="$(printf '%s\0' "$@" | sha256sum | awk '{print $1}')"
    exec {lock_fd}>"${REPORT_UI_WORK_DIR}/${key}.lock"
    flock -x "${lock_fd}"
    if [[ ! -f "${REPORT_UI_WORK_DIR}/${key}.status" ]]; then
        rc=0
        "$@" >"${REPORT_UI_WORK_DIR}/${key}.output" 2>&1 || rc=$?
        printf '%s\n' "${rc}" >"${REPORT_UI_WORK_DIR}/${key}.status"
    fi
    cat "${REPORT_UI_WORK_DIR}/${key}.output"
    rc="$(cat "${REPORT_UI_WORK_DIR}/${key}.status")"
    flock -u "${lock_fd}"
    exec {lock_fd}>&-
    return "${rc}"
}

report_ui_enqueue() {
    local limit="${LAB_REPORT_PARALLELISM:-4}" slot
    [[ "${limit}" =~ ^[1-9][0-9]*$ ]] || limit=4
    ((limit <= 8)) || limit=8
    while ((REPORT_UI_JOB_COUNT - REPORT_UI_JOB_WAITED >= limit)); do
        wait "${REPORT_UI_JOB_PIDS[REPORT_UI_JOB_WAITED]}" || true
        REPORT_UI_JOB_WAITED=$((REPORT_UI_JOB_WAITED + 1))
    done
    slot="$(printf '%06d' "${REPORT_UI_JOB_COUNT}")"
    (
        REPORT_UI_ROWS_FILE="${REPORT_UI_WORK_DIR}/row-${slot}"
        : >"${REPORT_UI_ROWS_FILE}"
        rc=0
        "$@" || rc=$?
        printf '%s\n' "${rc}" >"${REPORT_UI_WORK_DIR}/result-${slot}"
    ) &
    REPORT_UI_JOB_PIDS+=("$!")
    REPORT_UI_JOB_COUNT=$((REPORT_UI_JOB_COUNT + 1))
}

report_ui_finish() {
    local index slot rc
    for ((index=REPORT_UI_JOB_WAITED; index<REPORT_UI_JOB_COUNT; index++)); do
        wait "${REPORT_UI_JOB_PIDS[index]}" || true
    done
    for ((index=0; index<REPORT_UI_JOB_COUNT; index++)); do
        slot="$(printf '%06d' "${index}")"
        if [[ ! -f "${REPORT_UI_WORK_DIR}/result-${slot}" ]]; then
            report_ui_emit fail "Diagnostics" "Probe execution" "A report probe did not complete" "slot=${slot}"
            REPORT_UI_FAILURES=$((REPORT_UI_FAILURES + 1))
            continue
        fi
        cat "${REPORT_UI_WORK_DIR}/row-${slot}" >>"${REPORT_UI_ROWS_FILE}"
        rc="$(cat "${REPORT_UI_WORK_DIR}/result-${slot}")"
        ((rc == 0)) || REPORT_UI_FAILURES=$((REPORT_UI_FAILURES + 1))
    done
    REPORT_UI_JOB_COUNT=0
    REPORT_UI_JOB_WAITED=0
    REPORT_UI_JOB_PIDS=()
    if [[ "${LAB_REPORT_TIMING:-false}" == true ]]; then
        printf 'Read-only report probes completed in %ss.\n' "$((SECONDS - REPORT_UI_STARTED_SECONDS))" >&2
    fi
}

report_ui_one_line() {
    local value="${1:-}"
    value="${value//$'\t'/ }"
    value="${value//$'\r'/ }"
    value="${value//$'\n'/ | }"
    printf '%s' "${value}"
}

report_ui_first_line() {
    awk 'NF && $0 !~ /^\+/ { print; exit }'
}

report_ui_trim_detail() {
    sed -n '1,20p'
}

report_ui_emit() {
    local status="$1"
    local area="$2"
    local check="$3"
    local summary="$4"
    local detail="${5:-}"
    local fix="${6:-}"
    local graph="${7:-}"
    local query="${8:-}"

    if [[ -z "${REPORT_UI_ROWS_FILE:-}" ]]; then
        echo "report_ui_begin was not called" >&2
        return 1
    fi

    printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
        "$(report_ui_one_line "${status}")" \
        "$(report_ui_one_line "${area}")" \
        "$(report_ui_one_line "${check}")" \
        "$(report_ui_one_line "${summary}")" \
        "$(report_ui_one_line "${detail}")" \
        "$(report_ui_one_line "${fix}")" \
        "$(report_ui_one_line "${graph}")" \
        "$(report_ui_one_line "${query}")" >>"${REPORT_UI_ROWS_FILE}"
}

report_ui_check() {
    if [[ "${REPORT_UI_PARALLEL:-false}" == true ]]; then
        report_ui_enqueue report_ui_check_sync "$@"
    else
        report_ui_check_sync "$@"
    fi
}

report_ui_check_sync() {
    local severity="$1"
    local area="$2"
    local check="$3"
    local fix="${4:-}"
    local graph="${5:-}"
    local query="${6:-}"
    shift 6
    local output
    local status
    local summary
    local detail

    set +e
    case "${1:-}" in
        status_container_running|status_http_ok|status_gitea_public_ok)
            output="$(report_ui_cached_probe "$@" 2>&1)" ;;
        *) output="$("$@" 2>&1)" ;;
    esac
    status=$?
    set -e

    if [[ "${status}" -eq 0 ]]; then
        report_ui_emit ok "${area}" "${check}" "ok" "${output}"
        return 0
    fi

    summary="$(printf '%s\n' "${output}" | report_ui_first_line)"
    if [[ -z "${summary}" ]]; then
        summary="check exited with status ${status}"
    fi
    detail="$(printf '%s\n' "${output}" | report_ui_trim_detail)"
    if [[ "${severity}" == "fail" ]]; then
        report_ui_emit fail "${area}" "${check}" "${summary}" "${detail}" "${fix}" "${graph}" "${query}"
        return 1
    fi
    report_ui_emit warn "${area}" "${check}" "${summary}" "${detail}" "${fix}" "${graph}" "${query}"
    return 0
}

report_ui_render() {
    local title="$1"
    local -a args=(--title "${title}" --only "${REPORT_UI_ONLY}")

    if [[ "${REPORT_UI_DETAILS}" == "true" ]]; then
        args+=(--details)
    fi
    if [[ "${REPORT_UI_JSON}" == "true" ]]; then
        args+=(--json)
    fi

    if [[ "${REPORT_UI_STATUS_SUMMARY:-false}" == true && "${REPORT_UI_JSON}" != true ]]; then
        args+=(--status-summary)
    fi

    "${REPO_ROOT}/scripts/report-render" "${args[@]}" <"${REPORT_UI_ROWS_FILE}"

    if [[ "${REPORT_UI_JSON}" != "true" && "${REPORT_UI_STATUS_SUMMARY:-false}" != true ]] && truthy "${REPORT_UI_LOCAL_RCA:-false}"; then
        report_ui_local_rca "${title}"
    fi
}

report_ui_local_rca() {
    local title="$1"
    local routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-/data/homelab-ai-stack/models.env}"
    local provider="${LAB_DOCTOR_RCA_PROVIDER:-${LAB_AI_GATEWAY_PROVIDER:-}}"
    local model endpoint key

    if [[ -s "${routes_file}" ]]; then
        # shellcheck disable=SC1090
        . "${routes_file}"
    fi
    if [[ -z "${provider}" ]]; then
        if [[ -n "${AI_STACK_AGENT_SMART_MODEL:-}" ]]; then provider=omniroute; else provider=ollama; fi
    fi
    model="${LAB_DOCTOR_LOCAL_MODEL:-${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${LAB_OLLAMA_MODEL:-llama3.2:3b}}}}"
    case "${provider,,}" in
        ollama) endpoint="${LAB_DOCTOR_RCA_ENDPOINT:-${LAB_OLLAMA_URL:-http://127.0.0.1:11434}}" ;;
        omniroute|openai) endpoint="${LAB_DOCTOR_RCA_ENDPOINT:-${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}}" ;;
        *) echo "AI explanation unavailable: unsupported provider."; return 0 ;;
    esac
    key="${LAB_AI_GATEWAY_API_KEY:-${OMNIROUTE_API_KEY:-${HERMES_OMNIROUTE_API_KEY:-sk_omniroute}}}"
    LAB_REPORT_AI_PROVIDER="${provider,,}" LAB_REPORT_AI_MODEL="${model}" \
        LAB_REPORT_AI_ENDPOINT="${endpoint}" LAB_REPORT_AI_KEY="${key}" \
        python3 "${REPO_ROOT}/scripts/report-ai-explain.py" "${REPORT_UI_ROWS_FILE}" "${title}" || \
        echo "AI explanation unavailable; deterministic report remains available."
}
