#!/usr/bin/env bash
# scripts/onboard/steps/40-register.sh — wpisz node do inventory i commituj na branchu
#
# Efekty (wszystkie idempotentne):
#   1. Dopisuje blok <node> do inventory/topology.yaml
#   2. Tworzy hosts/<node>/services.yaml jeśli nie istnieje
#   3. git add + git commit na aktualnym branchu (NIE push — merge należy do operatora)
#
# Reload observera celowo poza tym krokiem — wykonywany ręcznie po merge→master,
# git pull na VPS i uruchomieniu 50-verify.sh.

set -euo pipefail

STEP_NAME="40-register"

: "${REPO_ROOT:?REPO_ROOT is not set — run via onboard.sh}"
: "${NODE_YAML:?NODE_YAML is not set — run via onboard.sh}"
: "${DRY_RUN:=0}"

if ! declare -f log >/dev/null 2>&1; then
    # shellcheck source=../lib/common.sh
    source "${REPO_ROOT}/scripts/onboard/lib/common.sh"
fi

NODE_ENTRY=$(yaml_get "${NODE_YAML}" "tailscale.hostname")
[[ -z "${NODE_ENTRY}" ]] && die "tailscale.hostname not set in ${NODE_YAML}"

TOPOLOGY="${REPO_ROOT}/inventory/topology.yaml"
SERVICES_YAML="${REPO_ROOT}/hosts/${NODE_ENTRY}/services.yaml"

# ── 1. inventory/topology.yaml ────────────────────────────────────────────────
step "[${STEP_NAME}] 1/3 inventory/topology.yaml"

_TOPOLOGY_BLOCK=$(cat << 'EOF'

  PLACEHOLDER:
    roles:
      - edge
    services:
      - node-agent
EOF
)
# Replace the PLACEHOLDER with the actual node name
_TOPOLOGY_BLOCK="${_TOPOLOGY_BLOCK//PLACEHOLDER/${NODE_ENTRY}}"

if grep -q "^  ${NODE_ENTRY}:" "${TOPOLOGY}"; then
    log "${NODE_ENTRY} already present in topology.yaml — skip"
else
    if [ "${DRY_RUN:-0}" = 1 ]; then
        dryrun "Would append to ${TOPOLOGY}:"
        echo "${_TOPOLOGY_BLOCK}"
    else
        printf '%s\n' "${_TOPOLOGY_BLOCK}" >> "${TOPOLOGY}"
        log "Appended ${NODE_ENTRY} block to topology.yaml"
    fi
fi

# ── 2. hosts/<node>/services.yaml ────────────────────────────────────────────
step "[${STEP_NAME}] 2/3 hosts/${NODE_ENTRY}/services.yaml"

if [[ -f "${SERVICES_YAML}" ]]; then
    log "services.yaml already exists — skip"
else
    if [ "${DRY_RUN:-0}" = 1 ]; then
        dryrun "Would create ${SERVICES_YAML}:"
        cat << EOF
host: ${NODE_ENTRY}

services:
  node-agent:
    role: node-stability-monitor
    deployment_model: docker-compose
    exposure: local-only
    offline_required: true
    depends_on:
      local: []
      external: []
    runtime:
      config_path: /opt/homelab/config/node-agent
      data_path: /opt/homelab/state
      logs_path: /opt/homelab/events
EOF
    else
        mkdir -p "${REPO_ROOT}/hosts/${NODE_ENTRY}"
        cat > "${SERVICES_YAML}" << EOF
host: ${NODE_ENTRY}

services:
  node-agent:
    role: node-stability-monitor
    deployment_model: docker-compose
    exposure: local-only
    offline_required: true
    depends_on:
      local: []
      external: []
    runtime:
      config_path: /opt/homelab/config/node-agent
      data_path: /opt/homelab/state
      logs_path: /opt/homelab/events
EOF
        log "Created ${SERVICES_YAML}"
    fi
fi

# ── 3. git commit ─────────────────────────────────────────────────────────────
step "[${STEP_NAME}] 3/3 git commit"

cd "${REPO_ROOT}"

_changed_files=()
git diff --quiet "${TOPOLOGY}" 2>/dev/null                || _changed_files+=("inventory/topology.yaml")
[[ -f "${SERVICES_YAML}" ]] && \
    git ls-files --error-unmatch "${SERVICES_YAML}" 2>/dev/null || \
    _changed_files+=("hosts/${NODE_ENTRY}/services.yaml")

# Re-check: is anything staged or unstaged for these paths?
_needs_commit=0
if git diff --quiet && git diff --cached --quiet; then
    # Nothing changed at all — may already be committed
    if git ls-files --error-unmatch "${TOPOLOGY}" "${SERVICES_YAML}" >/dev/null 2>&1 && \
       ! git diff HEAD -- "${TOPOLOGY}" "${SERVICES_YAML}" | grep -q .; then
        log "Nothing to commit — ${NODE_ENTRY} already registered and committed"
    else
        _needs_commit=1
    fi
else
    _needs_commit=1
fi

if [[ "${_needs_commit}" -eq 1 ]]; then
    run git add "inventory/topology.yaml" "hosts/${NODE_ENTRY}/services.yaml"
    run git commit -m "feat(onboard): register ${NODE_ENTRY} in topology + services.yaml"
    if [ "${DRY_RUN:-0}" != 1 ]; then
        log "Committed on $(git branch --show-current)"
        log "Next: agent.sh merge task/node-onboarding → master, git pull VPS, run 50-verify.sh"
    fi
fi

log "[${STEP_NAME}] done"
