#!/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:-true}"
# shellcheck disable=SC2034
REPORT_UI_VERBOSE=false
REPORT_UI_ROWS_FILE=""

report_ui_usage_flags() {
    cat <<'EOF'
Report UI flags:
  --all             Show ok, skip, warning, and failing items.
  --details         Show the compact report plus detail fields.
  --json            Print structured JSON.
  --no-local-rca    Do not ask the local AI gateway for the focused RCA summary.
  --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
                ;;
            --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_cleanup() {
    if [[ -n "${REPORT_UI_ROWS_FILE:-}" && -f "${REPORT_UI_ROWS_FILE}" ]]; then
        rm -f "${REPORT_UI_ROWS_FILE}"
    fi
    REPORT_UI_ROWS_FILE=""
}

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() {
    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
    output="$("$@" 2>&1)"
    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

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

    if [[ "${REPORT_UI_JSON}" != "true" ]] && truthy "${REPORT_UI_LOCAL_RCA:-true}"; 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 ollama_url="${LAB_OLLAMA_URL:-http://127.0.0.1:11434}"
    local omniroute_url="${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}"
    local omniroute_key="${LAB_AI_GATEWAY_API_KEY:-${OMNIROUTE_API_KEY:-${HERMES_OMNIROUTE_API_KEY:-sk_omniroute}}}"
    local model
    local problems
    local prompt
    local payload
    local response
    local answer
    local error_message
    local tags_response
    local curl_status
    local http_status

    problems="$(awk -F'\t' '
        ($1 == "fail" || $1 == "warn") {
            printf "- status=%s area=%s check=%s summary=%s detail=%s fix=%s\n", $1, $2, $3, $4, $5, $6
            count++
            if (count >= 12) exit
        }
    ' "${REPORT_UI_ROWS_FILE}")"
    if [[ -z "${problems}" ]]; then
        return 0
    fi

    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}}}}"

    printf '\n== AI RCA ==\n'
    if ! command -v curl >/dev/null 2>&1 || ! command -v jq >/dev/null 2>&1; then
        printf 'skipped: curl and jq are required to ask the AI gateway for RCA.\n'
        printf 'fix: install curl jq, or rerun with --no-local-rca.\n'
        return 0
    fi

    prompt="$(cat <<EOF
You are Jeannie, a local homelab SRE assistant. Use only the evidence below.
Homelab topology: Kubernetes runs on Pimox VMs; Debian hosts external services like Gitea, Dex, registry, Ollama, backups, and Jeannie; OCI edge proxies public traffic; RPi provides DNS/support services.

Task:
1. Pick the single highest-impact issue to focus first.
2. Give likely root cause, evidence, immediate mitigation, and long-term redesign.
3. Return exactly four bullets: Focus, Root cause, Mitigation, Redesign.
4. For Kubernetes pod/node issues, prefer read-only Holmes triage before mutation.
5. Keep it concise and practical. Do not invent commands not implied by the fix field.

Report title: ${title}
Problems:
${problems}
EOF
)"

    case "${provider,,}" in
        omniroute | openai)
            http_status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 5 "${omniroute_url%/}/models" 2>/dev/null || true)"
            if [[ "${http_status}" != "200" && "${http_status}" != "401" ]]; then
                printf 'skipped: OmniRoute is not reachable at %s; deterministic focus above is still valid.\n' "${omniroute_url%/}"
                return 0
            fi
            payload="$(jq -n \
                --arg model "${model}" \
                --arg prompt "${prompt}" \
                '{model: $model, messages: [{role: "user", content: $prompt}], stream: false, temperature: 0.1}')"
            set +e
            response="$(curl -sS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \
                -H "Authorization: Bearer ${omniroute_key}" \
                -H 'Content-Type: application/json' \
                -d "${payload}" \
                "${omniroute_url%/}/chat/completions" 2>/dev/null)"
            curl_status=$?
            set -e
            answer="$(printf '%s' "${response}" | jq -r '.choices[0].message.content // empty' 2>/dev/null || true)"
            error_message="$(printf '%s' "${response}" | jq -r '.error.message // empty' 2>/dev/null || true)"
            if [[ -z "${answer}" ]]; then
                if [[ "${curl_status}" -eq 28 ]]; then
                    printf 'skipped: OmniRoute model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}"
                elif [[ -n "${error_message}" ]]; then
                    printf 'skipped: OmniRoute returned no RCA using model %s: %s\n' "${model}" "${error_message}"
                else
                    printf 'skipped: OmniRoute returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}"
                fi
                return 0
            fi
            ;;
        *)
            tags_response="$(curl -fsS --connect-timeout 2 --max-time 5 "${ollama_url%/}/api/tags" 2>/dev/null || true)"
            if [[ -z "${tags_response}" ]]; then
                printf 'skipped: Ollama is not reachable at %s; deterministic focus above is still valid.\n' "${ollama_url%/}"
                return 0
            fi
            if ! printf '%s' "${tags_response}" | jq -e --arg model "${model}" '.models[]?.name == $model' >/dev/null 2>&1; then
                printf 'skipped: model %s is not installed in Ollama; deterministic focus above is still valid.\n' "${model}"
                printf 'hint: set LAB_DOCTOR_LOCAL_MODEL to one from `ollama list`, or pull %s.\n' "${model}"
                return 0
            fi

            payload="$(jq -n \
                --arg model "${model}" \
                --arg prompt "${prompt}" \
                '{model: $model, prompt: $prompt, stream: false, options: {temperature: 0.1}}')"
            set +e
            response="$(curl -fsS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \
                -H 'Content-Type: application/json' \
                -d "${payload}" \
                "${ollama_url%/}/api/generate" 2>/dev/null)"
            curl_status=$?
            set -e
            answer="$(printf '%s' "${response}" | jq -r '.response // empty' 2>/dev/null || true)"
            if [[ -z "${answer}" ]]; then
                if [[ "${curl_status}" -eq 28 ]]; then
                    printf 'skipped: model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}"
                    printf 'hint: use LAB_DOCTOR_LOCAL_MODEL=qwen2.5:0.5b or increase LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS.\n'
                else
                    printf 'skipped: Ollama returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}"
                fi
                return 0
            fi
            ;;
    esac

    printf '%s\n' "${answer}"
}
