#!/bin/bash
# =============================================================================
# status.sh — KiteStacks AutoSync health check
# =============================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/config/settings.conf"
STATE_FILE="/opt/kitestacks-autosync/.active_target"
WORK_DIR="/opt/kitestacks-autosync"

BOLD='\033[1m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'

ok()   { echo -e "  ${GREEN}✓${NC}  $1"; }
fail() { echo -e "  ${RED}✗${NC}  $1"; }
info() { echo -e "  ${CYAN}·${NC}  $1"; }

source "$CONFIG_FILE" 2>/dev/null || { echo "Config not found at $CONFIG_FILE"; exit 1; }

echo -e "\n${BOLD}╔══ KiteStacks AutoSync Status ════════════════════════════════╗${NC}"

# ── Service ───────────────────────────────────────────────────────────────────
echo -e "\n${BOLD}Service${NC}"
if systemctl is-active --quiet kitestacks-autosync 2>/dev/null; then
    ok "kitestacks-autosync is running"
else
    fail "kitestacks-autosync is NOT running"
    echo "     → sudo systemctl start kitestacks-autosync"
fi
systemctl is-enabled --quiet kitestacks-autosync 2>/dev/null \
    && ok "Enabled at boot" || info "Not enabled at boot"

# ── Active target ─────────────────────────────────────────────────────────────
echo -e "\n${BOLD}Active Target${NC}"
TARGET="$(cat "$STATE_FILE" 2>/dev/null || echo "test")"
if [[ "$TARGET" == "main" ]]; then
    ok "→ MAIN: ${FORGEJO_URL}/${FORGEJO_USER}/${MAIN_REPO}"
else
    info "→ TEST: ${FORGEJO_URL}/${FORGEJO_USER}/${TEST_REPO}"
    info "   (run 'sudo bash promote.sh' when you're happy with the test repo)"
fi

# ── Workspace ─────────────────────────────────────────────────────────────────
echo -e "\n${BOLD}Workspace${NC}"
RNAME="$([[ "$TARGET" == "main" ]] && echo "$MAIN_REPO" || echo "$TEST_REPO")"
RDIR="$WORK_DIR/$RNAME"

if [[ -d "$RDIR/.git" ]]; then
    ok "Cloned: $RDIR"
    VER=$(grep -oP '(?<=version:\s)[\d.]+' "$RDIR/README.md" 2>/dev/null | head -1 || echo "unknown")
    info "Current version : $VER"
    LAST=$(cd "$RDIR" && git log -1 --format="%h  %s  (%ar)" 2>/dev/null)
    info "Last commit     : $LAST"
    DOC_COUNT=$(ls "$RDIR/docs/"KiteStacks-Homelab-Documentation-v*.md 2>/dev/null | wc -l)
    info "Doc versions    : $DOC_COUNT file(s) in docs/"
else
    fail "Workspace not found — run setup.sh first"
fi

# ── Forgejo API ───────────────────────────────────────────────────────────────
echo -e "\n${BOLD}Forgejo Connectivity${NC}"
HTTP=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 \
    -H "Authorization: token $FORGEJO_TOKEN" \
    "${FORGEJO_URL}/api/v1/user" 2>/dev/null)
[[ "$HTTP" == "200" ]] && ok "API reachable ($FORGEJO_URL)" || fail "API returned HTTP $HTTP"

# ── Watch dirs ────────────────────────────────────────────────────────────────
echo -e "\n${BOLD}Watched Directories${NC}"
for d in $WATCH_DIRS; do
    if [[ -d "$d" ]]; then
        COUNT=$(find "$d" -type f 2>/dev/null | wc -l)
        ok "$d  ($COUNT files)"
    else
        fail "$d  (does not exist)"
    fi
done

# ── Recent logs ───────────────────────────────────────────────────────────────
echo -e "\n${BOLD}Recent Log Entries (last 10)${NC}"
journalctl -u kitestacks-autosync -n 10 --no-pager -q 2>/dev/null \
    | sed 's/^/  /' \
    || info "No journal entries yet."

echo -e "\n${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}"
echo -e "  Live logs: ${CYAN}journalctl -u kitestacks-autosync -f${NC}\n"
