#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

run_step() {
    local label="$1"
    shift

    printf '\n== %s ==\n' "${label}"
    "$@"
}

shell_files() {
    local path

    git -C "${REPO_ROOT}" ls-files | while IFS= read -r path; do
        case "${path}" in
            jeannie | *.sh)
                printf '%s\n' "${path}"
                ;;
            scripts/*)
                if head -n 1 "${REPO_ROOT}/${path}" | grep -Eq 'sh|bash'; then
                    printf '%s\n' "${path}"
                fi
                ;;
        esac
    done
}

validate_bash_syntax() {
    local files=()
    local file

    while IFS= read -r file; do
        files+=("${REPO_ROOT}/${file}")
    done < <(shell_files)

    if ((${#files[@]} == 0)); then
        echo "no shell files found"
        return 0
    fi
    bash -n "${files[@]}"
}

validate_shellcheck() {
    local files=()
    local file

    while IFS= read -r file; do
        files+=("${REPO_ROOT}/${file}")
    done < <(shell_files)

    if ! command -v shellcheck >/dev/null 2>&1; then
        echo "shellcheck not installed; skipping"
        return 0
    fi
    if ((${#files[@]} == 0)); then
        echo "no shell files found"
        return 0
    fi
    # Informational findings remain useful during focused reviews, but the
    # validation gate enforces warnings and errors consistently on CI hosts.
    shellcheck --severity=warning "${files[@]}"
}

validate_yaml() {
    if command -v ruby >/dev/null 2>&1; then
        ruby -e 'require "yaml"; (Dir["**/*.yml"] + Dir["**/*.yaml"]).each { |path| next if path.start_with?(".git/"); YAML.load_stream(File.read(path)) }; puts "yaml parse ok"'
        return 0
    fi
    echo "ruby not installed; skipping generic YAML parse"
}

validate_progressive_chart() {
    if ! command -v helm >/dev/null 2>&1; then
        echo "helm not installed; skipping progressive lab chart rendering"
        return 0
    fi
    helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" >/dev/null
    helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" --set canaryWeight=10 --set canaryFailure=true >/dev/null
    helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" --set canaryWeight=10 --set badReadiness=true >/dev/null
}

validate_tofu_fmt() {
    if ! command -v tofu >/dev/null 2>&1; then
        echo "tofu not installed; skipping fmt check"
        return 0
    fi
    tofu fmt -check -recursive "${REPO_ROOT}/bootstrap"
}

validate_go() {
    if ! command -v go >/dev/null 2>&1; then
        echo "go not installed; skipping Go checks"
        return 0
    fi
    local unformatted
    unformatted="$(gofmt -l "${REPO_ROOT}/cmd")"
    if [[ -n "${unformatted}" ]]; then
        printf 'Go files require formatting:\n%s\n' "${unformatted}" >&2
        return 1
    fi
    GOCACHE="${GOCACHE:-${REPO_ROOT}/.lab/go-build-cache}" go test ./...
}

validate_security_static() {
    "${REPO_ROOT}/scripts/validate-tailnet-policy"
    if command -v trivy >/dev/null 2>&1; then
        trivy config --quiet "${REPO_ROOT}"
    else
        echo "trivy not installed; skipping IaC security static scan"
    fi
}

validate_unit_tests() {
    "${REPO_ROOT}/tests/jeannie-unit"
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_dex_drift.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_opentelemetry_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_gateway_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_secrets_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_progressive_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ai_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ai_lab_suite.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_retrieval_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_context_lab.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_focus.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_app_snapshot.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_go_launchers.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_focus.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_stale_pod_candidate.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_exporter_access.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_loki.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_debian.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_monitoring_readiness.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_searxng_pipeline.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_privacy_services_pipeline.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_k3s_storage.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_holmes_evidence.py'
    if [[ -x "${LAB_HOLMES_ADAPTER_PYTHON:-/home/jv/.local/share/pipx/venvs/holmesgpt/bin/python}" ]]; then
        "${LAB_HOLMES_ADAPTER_PYTHON:-/home/jv/.local/share/pipx/venvs/holmesgpt/bin/python}" -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ollama_tool_call_adapter.py'
    else
        echo "Holmes Python environment unavailable; Ollama adapter tests skipped"
    fi
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_report_ai_explain.py'
    python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_model_lab.py'
}

main() {
    cd "${REPO_ROOT}"
    run_step "Inventory" "${REPO_ROOT}/scripts/validate-homelab-inventory" "${HOMELAB_INVENTORY_FILE:-${REPO_ROOT}/homelab.yml}"
    run_step "Unit tests" validate_unit_tests
    run_step "Generated docs" "${REPO_ROOT}/scripts/render-docs" --check
    run_step "Bash syntax" validate_bash_syntax
    run_step "Shellcheck" validate_shellcheck
    run_step "YAML parse" validate_yaml
    run_step "Progressive lab chart" validate_progressive_chart
    run_step "Go checks" validate_go
    run_step "OpenTofu formatting" validate_tofu_fmt
    run_step "Security static checks" validate_security_static
}

main "$@"
