#!/bin/bash
# =============================================================================
# diag_info.sh — Kompletní přehled stavu Terkom Diagnostiky
# =============================================================================
# Použití:
#   sudo ./diag_info.sh
#   sudo ./diag_info.sh --errors-only   # jen chyby (dnes + 5 dní)
#   sudo ./diag_info.sh --profile-only  # jen aktivní profil
#   sudo ./diag_info.sh --version-only  # jen verze a stav
# =============================================================================

if [ -z "${BASH_VERSION:-}" ]; then
    if [ -f "$0" ]; then exec bash "$0" "$@"; fi
    echo "[ERROR] Vyžaduje bash. Spusť: curl -fsSL URL | sudo bash" >&2; exit 1
fi
set -uo pipefail

TERKOM_HOME="${TERKOM_HOME:-/opt/terkom-ng/terkom}"
SCRIPT_DIR="${SCRIPT_DIR:-$TERKOM_HOME/scripts}"
DIAG_SCRIPT="${DIAG_SCRIPT:-$SCRIPT_DIR/terkom-diagnostic.sh}"
RUNTIME="${RUNTIME:-$TERKOM_HOME/terkom-diagnostic.runtime.yaml}"
CONFIG_FILE="${CONFIG_FILE:-$TERKOM_HOME/config-local.yaml}"
PERSIST_BASE="${PERSIST_BASE:-$SCRIPT_DIR/diagnostic}"
ACTIVE_PROFILE_FILE="${ACTIVE_PROFILE_FILE:-$TERKOM_HOME/terkom-diagnostic.active-profile}"
ERRORS_DAYS="${ERRORS_DAYS:-5}"
TIMER_UNIT="${TIMER_UNIT:-terkom-diagnostic.timer}"
SERVICE_UNIT="${SERVICE_UNIT:-terkom-diagnostic.service}"
LOG_LINES="${LOG_LINES:-20}"

# Detekce barev
if [ -t 1 ] && [ "${TERM:-dumb}" != "dumb" ] && tput colors >/dev/null 2>&1 && [ "$(tput colors 2>/dev/null)" -ge 8 ]; then
    RED=$'\033[0;31m' GREEN=$'\033[0;32m' YELLOW=$'\033[1;33m'
    CYAN=$'\033[0;36m' BOLD=$'\033[1m' DIM=$'\033[2m' NC=$'\033[0m'
else
    RED='' GREEN='' YELLOW='' CYAN='' BOLD='' DIM='' NC=''
fi

SHOW_VERSION=true
SHOW_PROFILE=true
SHOW_ERRORS=true
FAILED=0

for arg in "$@"; do
    case "$arg" in
        --errors-only)  SHOW_VERSION=false; SHOW_PROFILE=false ;;
        --profile-only) SHOW_VERSION=false; SHOW_ERRORS=false ;;
        --version-only) SHOW_PROFILE=false; SHOW_ERRORS=false ;;
    esac
done

ok()   { printf "%s[OK]%s  %s\n"   "$GREEN"  "$NC" "$*"; }
fail() { printf "%s[!!]%s  %s\n"   "$RED"    "$NC" "$*"; FAILED=1; }
warn() { printf "%s[??]%s  %s\n"   "$YELLOW" "$NC" "$*"; }
hdr()  { printf "\n%s=== %s ===%s\n" "$BOLD" "$*" "$NC"; }
info() { printf "      %s\n" "$*"; }
dim()  { printf "%s      %s%s\n"   "$DIM" "$*" "$NC"; }
sep()  { printf "      %s\n" "------------------------------------------------------------"; }
path_state() {
    local label="$1" path="$2" extra="${3:-}"
    if [ -e "$path" ]; then
        ok "$(printf '%-21s' "$label") $path${extra}"
    else
        warn "$(printf '%-21s' "$label") chybi: $path${extra}"
    fi
}

profile_description() {
    case "$1" in
        1) echo "Standard: bezne terminaly, restart Terkom po 1 dead failu, reboot po 3" ;;
        2) echo "Vydejni freeze protection: rychly restart Terkomu, reboot po 2 dead/local UI failech" ;;
        3) echo "Network diagnostic / Caslav: lokalne OK, remote TCP / server / sit" ;;
        4) echo "Konzervativni monitoring: pomalejsi reakce, delsi doba pred rebootem, mene mailu" ;;
        5) echo "Servisni agresivni: kratkodobe testovani pod dohledem" ;;
        6) echo "Legacy: spicka provozu, sit-only reboot po 6 cyklech" ;;
        7) echo "Legacy: puvodni laborator / ultra agresivni profil" ;;
        8) echo "Legacy: puvodni kompromis, sit-only reboot po 5 cyklech" ;;
        9) echo "Legacy: rychly sit-only reboot, network restart po 2, reboot po 3" ;;
        *) echo "(neznamy profil)" ;;
    esac
}
profile_timer() { case "$1" in 1|3|4) echo "20s";; 2|6|8|9) echo "10s";; 5|7) echo "5s";; *) echo "?";; esac; }
profile_mode()  { case "$1" in 1|3|4) echo "NORMAL";; 2|6|8|9) echo "FAST";; 5|7) echo "ULTRA";; *) echo "?";; esac; }

# Pomocná funkce: najde snapshot složky přes celý PERSIST_BASE (i stojan_X podsložky)
find_snapshots() {
    find "$PERSIST_BASE" -mindepth 1 -maxdepth 2 -type d \
        -name "????-??-??_??-??-??_*" 2>/dev/null | sort -r
}

print_recent_logs() {
    printf "\n"
    hdr "Posledni logy"
    if command -v journalctl >/dev/null 2>&1; then
        journalctl -u "$SERVICE_UNIT" -n "$LOG_LINES" --no-pager 2>/dev/null \
            | sed 's/^/      /' || warn "Logy se nepodarilo nacist pres journalctl."
    else
        warn "journalctl neni dostupny."
    fi
}

# ─────────────────────────────────────────────────────────────────────────────
printf "\n"
printf "%s============================================================%s\n" "$BOLD" "$NC"
printf "%s  Terkom Info Diagnostic%s\n" "$BOLD" "$NC"
printf "%s============================================================%s\n" "$BOLD" "$NC"

# ─── SEKCE 1: VERZE A STAV ───────────────────────────────────────────────────
if [ "$SHOW_VERSION" = "true" ]; then
    hdr "Verze a stav"

    # Watchdog skript
    if [ -f "$DIAG_SCRIPT" ]; then
        LOCAL_VER="$(grep -m1 'SCRIPT_VERSION=' "$DIAG_SCRIPT" 2>/dev/null | tr -d '"' | cut -d= -f2 | xargs || true)"
        ok "Verze watchdogu:  ${LOCAL_VER:-neznama}"
    else
        fail "Watchdog skript nenalezen: $DIAG_SCRIPT"
        LOCAL_VER=""
    fi

    # Marker v config
    if [ -f "$CONFIG_FILE" ]; then
        MARKER="$(grep -iE '"?description"?[[:space:]]*:' "$CONFIG_FILE" 2>/dev/null \
            | grep -oE 'DIAG_v[^ "]*|---DIA_v[^ "]*' | head -1 || true)"
        info "Marker v config:   ${MARKER:-(nenalezen)}"
    else
        info "Marker v config:   (config-local.yaml nenalezen)"
    fi

    # Helper skripty
    printf "\n"
    for _h in diag_info.sh apply_diagnostic_profile.sh check_diagnostic.sh; do
        if [ -f "$SCRIPT_DIR/$_h" ]; then
            ok "Helper: $_h"
        else
            warn "Helper chybí: $_h  (spusť update)"
        fi
    done

    # Timer a poslední běh
    printf "\n"
    if systemctl is-active --quiet "$TIMER_UNIT" 2>/dev/null; then
        _enabled=""
        systemctl is-enabled --quiet "$TIMER_UNIT" 2>/dev/null && _enabled="  |  enabled"
        ok "Timer:             aktivni${_enabled}"
    else
        fail "Timer:             NEAKTIVNI ($TIMER_UNIT)"
        systemctl is-enabled --quiet "$TIMER_UNIT" 2>/dev/null \
            || warn "Timer neni enabled — po rebootu se nespusti automaticky"
    fi

    LAST_RUN="$(systemctl show "$SERVICE_UNIT" \
        --property=ExecMainExitTimestamp --value 2>/dev/null | xargs || true)"
    [ -n "$LAST_RUN" ] && [ "$LAST_RUN" != "n/a" ] && info "Posledni beh:      $LAST_RUN"

    EXIT_CODE="$(systemctl show "$SERVICE_UNIT" \
        --property=ExecMainStatus --value 2>/dev/null | xargs || true)"
    if [ -n "$EXIT_CODE" ] && [ "$EXIT_CODE" != "0" ] && [ "$EXIT_CODE" != "" ]; then
        warn "Posledni beh skoncil s exit kodem: $EXIT_CODE"
    fi

    # Systemd status — timer
    printf "\n"
    if systemctl is-active --quiet "$TIMER_UNIT" 2>/dev/null; then
        ok "$TIMER_UNIT:"
    else
        fail "$TIMER_UNIT:"
    fi
    systemctl status "$TIMER_UNIT" --no-pager -l 2>/dev/null \
        | head -n 8 | sed 's/^/        /' || true

    # Systemd status — service
    printf "\n"
    _svc_ok=true
    systemctl is-active --quiet "$SERVICE_UNIT" 2>/dev/null || _svc_ok=false
    if [ "$_svc_ok" = "true" ]; then
        ok "$SERVICE_UNIT:"
    else
        info "$SERVICE_UNIT:"
    fi
    systemctl status "$SERVICE_UNIT" --no-pager -l 2>/dev/null \
        | head -n 8 | sed 's/^/        /' || true

    hdr "Soubory na zarizeni"
    path_state "Watchdog skript:" "$DIAG_SCRIPT"
    path_state "diag_info.sh:" "$SCRIPT_DIR/diag_info.sh"
    path_state "check_diagnostic.sh:" "$SCRIPT_DIR/check_diagnostic.sh"
    path_state "apply profil:" "$SCRIPT_DIR/apply_diagnostic_profile.sh"
    path_state "runtime.yaml:" "$RUNTIME"
    path_state "active profil:" "$ACTIVE_PROFILE_FILE"
    path_state "config-local:" "$CONFIG_FILE"
    path_state "snapshoty:" "$PERSIST_BASE"

    print_recent_logs
fi

# ─── SEKCE 2: AKTIVNÍ PROFIL ─────────────────────────────────────────────────
if [ "$SHOW_PROFILE" = "true" ]; then
    hdr "Aktivni profil"

    ACTIVE_ID=""
    [ -f "$ACTIVE_PROFILE_FILE" ] && ACTIVE_ID="$(cat "$ACTIVE_PROFILE_FILE" 2>/dev/null | xargs || true)"

    if [ -n "$ACTIVE_ID" ]; then
        ok "Profil c. ${ACTIVE_ID}  |  timer: $(profile_timer "$ACTIVE_ID")  |  rezim: $(profile_mode "$ACTIVE_ID")"
        info "Popis:             $(profile_description "$ACTIVE_ID")"
    else
        warn "Aktivni profil: (nenalezen — nastaven rucne nebo pred zavedenim persistence)"
    fi

    if [ -f "$RUNTIME" ]; then
        printf "\n"
        dim "runtime.yaml:"
        grep -v '^#\|^$' "$RUNTIME" 2>/dev/null | sed 's/^/        /' || true
    else
        info "runtime.yaml:      (nenalezen: $RUNTIME)"
    fi
fi

# ─── SEKCE 3: CHYBY DNES ─────────────────────────────────────────────────────
if [ "$SHOW_ERRORS" = "true" ]; then
    hdr "Chyby dnes"

    TODAY="$(date '+%Y-%m-%d')"
    today_count=0
    today_types=""

    if [ -d "$PERSIST_BASE" ]; then
        while IFS= read -r snap_dir; do
            snap_name="$(basename "$snap_dir")"
            snap_day="${snap_name:0:10}"
            snap_type="${snap_name#????-??-??_??-??-??_}"
            if [ "$snap_day" = "$TODAY" ]; then
                today_count=$(( today_count + 1 ))
                if [ -z "$today_types" ]; then
                    today_types="$snap_type"
                elif [[ "$today_types" != *"$snap_type"* ]]; then
                    today_types="${today_types}, ${snap_type}"
                fi
            fi
        done < <(find_snapshots)
    fi

    if [ "$today_count" -eq 0 ]; then
        ok "Dnes zadne incidenty  (${TODAY})"
    else
        fail "Dnes x${today_count} incidentu  (${TODAY})  —  ${today_types}"
    fi

# ─── SEKCE 4: CHYBY ZA POSLEDNÍCH N DNÍ ─────────────────────────────────────
    hdr "Chyby za poslednich ${ERRORS_DAYS} dni"

    if [ ! -d "$PERSIST_BASE" ]; then
        info "Slozka snapshotu neexistuje: $PERSIST_BASE"
    else
        declare -A day_counts
        declare -A day_types

        for i in $(seq 0 $((ERRORS_DAYS - 1))); do
            DAY="$(date -d "-${i} days" '+%Y-%m-%d' 2>/dev/null \
                || date -v-${i}d '+%Y-%m-%d' 2>/dev/null || true)"
            [ -z "$DAY" ] && continue
            day_counts["$DAY"]=0
            day_types["$DAY"]=""
        done

        while IFS= read -r snap_dir; do
            [ -d "$snap_dir" ] || continue
            snap_name="$(basename "$snap_dir")"
            snap_day="${snap_name:0:10}"
            snap_type="${snap_name#????-??-??_??-??-??_}"
            if [[ -v day_counts["$snap_day"] ]]; then
                day_counts["$snap_day"]=$(( day_counts["$snap_day"] + 1 ))
                existing="${day_types[$snap_day]}"
                if [ -z "$existing" ]; then
                    day_types["$snap_day"]="$snap_type"
                elif [[ "$existing" != *"$snap_type"* ]]; then
                    day_types["$snap_day"]="${existing}, ${snap_type}"
                fi
            fi
        done < <(find_snapshots)

        printf "\n"
        printf "      %-12s  %-7s  %s\n" "Den" "Pocet" "Typy problemu"
        sep
        for i in $(seq 0 $((ERRORS_DAYS - 1))); do
            DAY="$(date -d "-${i} days" '+%Y-%m-%d' 2>/dev/null \
                || date -v-${i}d '+%Y-%m-%d' 2>/dev/null || true)"
            [ -z "$DAY" ] && continue
            cnt="${day_counts[$DAY]:-0}"
            types="${day_types[$DAY]:-}"
            if [ "$cnt" -gt 0 ]; then
                printf "  %s%-12s  x%-6s%s  %s\n" "$RED" "$DAY" "$cnt" "$NC" "$types"
            else
                printf "  %s%-12s  %-7s  bez incidentu%s\n" "$DIM" "$DAY" "x0" "$NC"
            fi
        done

        total_count=0
        for i in $(seq 0 $((ERRORS_DAYS - 1))); do
            DAY="$(date -d "-${i} days" '+%Y-%m-%d' 2>/dev/null \
                || date -v-${i}d '+%Y-%m-%d' 2>/dev/null || true)"
            [ -z "$DAY" ] && continue
            total_count=$(( total_count + ${day_counts[$DAY]:-0} ))
        done

        printf "\n"
        if [ "$total_count" -eq 0 ]; then
            ok "Zadne incidenty za poslednich ${ERRORS_DAYS} dni."
        else
            info "Celkem incidentu za ${ERRORS_DAYS} dni: ${total_count}"
            printf "\n"
            dim "Rozpad podle typu:"
            CUTOFF="$(date -d "-${ERRORS_DAYS} days" '+%Y-%m-%d' 2>/dev/null || true)"
            declare -A type_totals
            while IFS= read -r snap_dir; do
                [ -d "$snap_dir" ] || continue
                snap_name="$(basename "$snap_dir")"
                snap_day="${snap_name:0:10}"
                snap_type="${snap_name#????-??-??_??-??-??_}"
                if [[ "$snap_day" > "$CUTOFF" ]] || [[ "$snap_day" = "$CUTOFF" ]]; then
                    type_totals["$snap_type"]=$(( ${type_totals[$snap_type]:-0} + 1 ))
                fi
            done < <(find_snapshots)
            for t in "${!type_totals[@]}"; do
                printf "        %-42s  x%s\n" "$t" "${type_totals[$t]}"
            done | sort
        fi
    fi
fi

# ─── VÝSLEDEK ─────────────────────────────────────────────────────────────────
printf "\n"
printf "%s============================================================%s\n" "$BOLD" "$NC"
if [ "$FAILED" -eq 0 ]; then
    printf "%s[OK]  Diagnostika bezi spravne.%s\n" "$GREEN" "$NC"
else
    printf "%s[!!]  Nalezeny problemy — viz [!!] radky vyse.%s\n" "$RED" "$NC"
    printf "      Reinstalace: curl -fsSL https://cdn.public.altisima.cz/diagnostika/install_diagnostic.sh | sudo env FORCE_REINSTALL=1 bash\n"
fi
printf "%s============================================================%s\n" "$BOLD" "$NC"

printf "\n"
printf "%s  Tipy:%s\n" "$DIM" "$NC"
printf "    --errors-only    jen chyby dnes + 5 dni\n"
printf "    --profile-only   jen aktivni profil\n"
printf "    --version-only   jen verze a stav\n"
printf "    sudo journalctl -fu terkom-diagnostic.service\n"
printf "\n"
