#!/usr/bin/bash
#
# Generate Weekly Report - Génère un rapport HTML hebdomadaire des consommations
#
# Usage: generate-weekly-report [WEEK_OFFSET]
#   WEEK_OFFSET: Nombre de semaines dans le passé (défaut: 0 = semaine actuelle)
#

# set -euo pipefail

trap onERR ERR

onERR() {
    echo "ERROR" >&2
}

export LC_ALL=C
PROGNAME=${0##*/}
ZLCCLI=${ZLCCLI:-zlccli}

# Load environment
[[ -f /etc/profile.d/logcenter-path.sh ]] && source /etc/profile.d/logcenter-path.sh

# Paramètres
WEEK_OFFSET=${1:-0}
CURRENT_DATE=$(date +%Y-%m-%d)

# Calculer les dates de début et fin de la semaine
get_week_dates() {
    local offset=$1
    local base_date=$(date -d "$CURRENT_DATE -$((offset * 7)) days" +%Y-%m-%d)

    # Trouver le lundi de cette semaine (ISO 8601)
    local dow=$(date -d "$base_date" +%u)  # 1=lundi, 7=dimanche
    local monday=$(date -d "$base_date -$((dow - 1)) days" +%Y-%m-%d)
    local sunday=$(date -d "$monday +6 days" +%Y-%m-%d)

    echo "$monday $sunday"
}

# Récupérer les données d'usage pour une période donnée
get_usage_data() {
    local start_date=$1
    local end_date=$2

    # Récupérer les données des archives
    ${ZLCCLI} list-archives "fdate >= '$start_date' and fdate <= '$end_date'" 2>/dev/null || echo ""
}

# Calculer le total par machine
calculate_per_host_totals() {
    local data=$1
    echo "$data" | awk -F'\t' 'NR>1 {host[$2]+=$8} END {for(h in host) print h "\t" host[h]}' | sort -t$'\t' -k2 -rn
}

# Calculer le total global
calculate_global_total() {
    local data=$1
    echo "$data" | awk -F'\t' 'NR>1 {sum+=$8} END {print sum}'
}

# Format une valeur en pourcentage d'un maximum
# $1: value
# $2: max
calculate_percent() {
    awk -v "value=$1" -v "max=$2" 'BEGIN {printf "%.1f", (value && max) ? (value/max)*100 : 0.0}'
}

# Formater les bytes en format lisible
format_bytes() {
    local bytes=$1
    if [[ -z $bytes || $bytes -eq 0 ]]; then
        echo "0 o"
        return
    fi

    awk -v bytes="$bytes" 'BEGIN {
        split("o Ko Mo Go To", units)
        size = bytes
        unit = 1
        while (size >= 1024 && unit < 5) {
            size = size / 1024
            unit++
        }
        printf "%.2f %s", size, units[unit]
    }'
}

# Récupérer les données de la semaine actuelle
read -r current_monday current_sunday < <(get_week_dates $WEEK_OFFSET)
echo "Génération du rapport pour la semaine du $current_monday au $current_sunday..." >&2

# Récupérer les données jour par jour pour les 28 derniers jours (4 semaines)
declare -a DAY_TOTALS
declare -a DAY_DATES
declare -a DAY_LABELS

echo "Collecte des données des 28 derniers jours..." >&2
for i in {27..0}; do
    day_date=$(date -d "$current_sunday -$i days" +%Y-%m-%d)
    idx=$((27-i))
    DAY_DATES[$idx]="$day_date"
    DAY_LABELS[$idx]="$(LANG=fr_FR.UTF-8 date -d "$day_date" +%a) $(date -d "$day_date" +%d/%m)"

    echo "  - Récupération données du $day_date..." >&2
    day_data=$(get_usage_data "$day_date" "$day_date")
    total=$(calculate_global_total "$day_data")
    DAY_TOTALS[$idx]=${total:-0}
done

# Calculer le total de la semaine actuelle
CURRENT_WEEK_DATA=$(get_usage_data "$current_monday" "$current_sunday")
CURRENT_TOTAL=$(calculate_global_total "$CURRENT_WEEK_DATA")
PER_HOST_DATA=$(calculate_per_host_totals "$CURRENT_WEEK_DATA")

# Récupérer les usages actuels
ARCHIVES_USAGE=$(${ZLCCLI} get-archives-usage 2>/dev/null || echo "0	0")
read -r ARCHIVES_USED ARCHIVES_MAX <<< "$ARCHIVES_USAGE"

# Essayer de récupérer l'usage Elastic (peut échouer si pas d'option)
# Supporte les variables d'environnement ELASTIC_USED/ELASTIC_MAX en fallback
if [[ -n ${ELASTIC_USED:-} && -n ${ELASTIC_MAX:-} ]]; then
    HAS_ELASTIC=true
else
    ELASTIC_USAGE=$(${ZLCCLI} get-elastic-usage 2>/dev/null || echo "")
    if [[ -n $ELASTIC_USAGE ]]; then
        read -r ELASTIC_USED ELASTIC_MAX <<< "$ELASTIC_USAGE"
        HAS_ELASTIC=true
    else
        ELASTIC_USED=0
        ELASTIC_MAX=0
        HAS_ELASTIC=false
    fi
fi

# Générer le top 10 des machines
TOP10=$(echo "$PER_HOST_DATA" | head -10)

# Calculer les pourcentages d'usage
ARCHIVES_PERCENT=$(calculate_percent "$ARCHIVES_USED" "$ARCHIVES_MAX")
ARCHIVES_BAR_PERCENT=$(awk -v "p=$ARCHIVES_PERCENT" 'BEGIN {printf "%.1f", (p > 100 ? 100 : p)}')
if [[ $HAS_ELASTIC == true ]]; then
    ELASTIC_PERCENT=$(calculate_percent "$ELASTIC_USED" "$ELASTIC_MAX")
    ELASTIC_BAR_PERCENT=$(awk -v "p=$ELASTIC_PERCENT" 'BEGIN {printf "%.1f", (p > 100 ? 100 : p)}')
    CARD_WIDTH="31"
else
    CARD_WIDTH="48"
fi

# Générer le HTML (email-compatible: all inline styles, table layout, no SVG)
cat <<EOF
<!DOCTYPE html>
<html lang="fr" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--[if mso]>
    <style type="text/css">
        table { border-collapse: collapse; }
        td { font-family: Arial, sans-serif; }
    </style>
    <![endif]-->
    <style type="text/css">
        /* Print colors - stripped by email clients, used by browsers */
        @media print {
            * { print-color-adjust: exact !important; -webkit-print-color-adjust: exact !important; }
            .no-print { display: none !important; }
        }
        /* Also apply for screen in case of browser viewing */
        [bgcolor], th, td, div { print-color-adjust: exact; -webkit-print-color-adjust: exact; }
    </style>
    <title>Rapport Hebdomadaire LogVault - Semaine $(date -d "$current_monday" +%V) $(date -d "$current_monday" +%Y)</title>
</head>
<body style="margin:0; padding:0; background-color:#f5f5f5; font-family:Arial, Helvetica, sans-serif;" bgcolor="#f5f5f5">

<!-- Outer wrapper for centering -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f5f5f5;" bgcolor="#f5f5f5">
<tr><td align="center" style="padding:20px 10px;">

<!-- Main content table -->
<table role="presentation" width="900" cellpadding="0" cellspacing="0" border="0" style="max-width:900px; width:100%;">

    <!-- Header -->
    <tr><td bgcolor="#1a9ab5" style="padding:30px;">
        <h1 style="margin:0 0 10px 0; font-size:24px; color:#ffffff; font-family:Arial,Helvetica,sans-serif;">&#x1F4CA; Rapport Hebdomadaire LogVault</h1>
        <p style="margin:0; font-size:16px; color:#ffffff;">Semaine $(date -d "$current_monday" +%V) - Du $(date -d "$current_monday" +%d/%m/%Y) au $(date -d "$current_sunday" +%d/%m/%Y)</p>
        <p style="margin:10px 0 0 0; font-size:13px; color:#d0eef3;">G&eacute;n&eacute;r&eacute; le $(date +%d/%m/%Y) &agrave; $(date +%H:%M)</p>
    </td></tr>

    <!-- Spacer -->
    <tr><td style="padding:10px 0;"></td></tr>

    <!-- Summary cards -->
    <tr><td>
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
            <!-- Card: Archives -->
            <td width="${CARD_WIDTH}%" valign="top" style="background-color:#ffffff; padding:20px; border:1px solid #e0e0e0; " bgcolor="#ffffff">
                <h2 style="margin:0 0 15px 0; color:#17b8ce; font-size:18px; font-family:Arial,Helvetica,sans-serif; border-bottom:2px solid #17b8ce; padding-bottom:10px;">&#x1F4BE; Archives</h2>
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td style="padding:8px 0; color:#555555; border-bottom:1px solid #eeeeee; font-size:13px;">Utilis&eacute;</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce; border-bottom:1px solid #eeeeee;">$(format_bytes $ARCHIVES_USED)</td>
                    </tr>
                    <tr>
                        <td style="padding:8px 0; color:#555555; border-bottom:1px solid #eeeeee; font-size:13px;">Total</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce; border-bottom:1px solid #eeeeee;">$(format_bytes $ARCHIVES_MAX)</td>
                    </tr>
                    <tr>
                        <td style="padding:8px 0; color:#555555; font-size:13px;">Occupation</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce;">${ARCHIVES_PERCENT}%</td>
                    </tr>
                </table>
                <!-- Progress bar -->
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:8px;">
                <tr>
                    <td bgcolor="#e0e0e0" style="height:16px;">
                        <table role="presentation" width="${ARCHIVES_BAR_PERCENT}%" cellpadding="0" cellspacing="0" border="0">
                        <tr><td bgcolor="#17b8ce" style="height:16px; font-size:1px; line-height:1px;">&nbsp;</td></tr>
                        </table>
                    </td>
                </tr>
                </table>
            </td>

            <!-- Gutter -->
            <td width="3%"></td>

            <!-- Card: Volume de la semaine -->
            <td width="${CARD_WIDTH}%" valign="top" style="background-color:#ffffff; padding:20px; border:1px solid #e0e0e0; " bgcolor="#ffffff">
                <h2 style="margin:0 0 15px 0; color:#17b8ce; font-size:18px; font-family:Arial,Helvetica,sans-serif; border-bottom:2px solid #17b8ce; padding-bottom:10px;">&#x1F4C8; Volume semaine</h2>
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td style="padding:8px 0; color:#555555; border-bottom:1px solid #eeeeee; font-size:13px;">Total re&ccedil;u</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce; border-bottom:1px solid #eeeeee;">$(format_bytes ${CURRENT_TOTAL:-0})</td>
                    </tr>
                    <tr>
                        <td style="padding:8px 0; color:#555555; font-size:13px;">Machines</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce;">$(echo "$PER_HOST_DATA" | wc -l)</td>
                    </tr>
                </table>
            </td>
EOF

# Card Elastic (conditionnel, 3ème colonne)
if [[ $HAS_ELASTIC == true ]]; then
cat <<EOF

            <!-- Gutter -->
            <td width="3%"></td>

            <!-- Card: Indexation -->
            <td width="31%" valign="top" style="background-color:#ffffff; padding:20px; border:1px solid #e0e0e0; " bgcolor="#ffffff">
                <h2 style="margin:0 0 15px 0; color:#17b8ce; font-size:18px; font-family:Arial,Helvetica,sans-serif; border-bottom:2px solid #17b8ce; padding-bottom:10px;">&#x1F50D; Indexation</h2>
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td style="padding:8px 0; color:#555555; border-bottom:1px solid #eeeeee; font-size:13px;">Utilis&eacute;</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce; border-bottom:1px solid #eeeeee;">$(format_bytes $ELASTIC_USED)</td>
                    </tr>
                    <tr>
                        <td style="padding:8px 0; color:#555555; border-bottom:1px solid #eeeeee; font-size:13px;">Total</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce; border-bottom:1px solid #eeeeee;">$(format_bytes $ELASTIC_MAX)</td>
                    </tr>
                    <tr>
                        <td style="padding:8px 0; color:#555555; font-size:13px;">Occupation</td>
                        <td style="padding:8px 0; text-align:right; font-size:15px; font-weight:bold; color:#17b8ce;">${ELASTIC_PERCENT}%</td>
                    </tr>
                </table>
                <!-- Progress bar -->
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:8px;">
                <tr>
                    <td bgcolor="#e0e0e0" style="height:16px;">
                        <table role="presentation" width="${ELASTIC_BAR_PERCENT}%" cellpadding="0" cellspacing="0" border="0">
                        <tr><td bgcolor="#17b8ce" style="height:16px; font-size:1px; line-height:1px;">&nbsp;</td></tr>
                        </table>
                    </td>
                </tr>
                </table>
            </td>
EOF
fi

cat <<EOF
        </tr>
        </table>
    </td></tr>
EOF

# Calculer les valeurs pour le graphique
MAX_VALUE=0
for i in {0..27}; do
    if [[ ${DAY_TOTALS[$i]} -gt $MAX_VALUE ]]; then
        MAX_VALUE=${DAY_TOTALS[$i]}
    fi
done

# Ajouter une marge de 10% au max
MAX_VALUE=$(awk -v max="$MAX_VALUE" 'BEGIN {printf "%.0f", max * 1.1}')

# Si MAX_VALUE est 0, on met une valeur par défaut
[[ $MAX_VALUE -eq 0 ]] && MAX_VALUE=1000000000

CHART_HEIGHT=150

cat <<EOF

    <!-- Spacer -->
    <tr><td style="padding:10px 0;"></td></tr>

    <!-- Bar chart -->
    <tr><td style="background-color:#ffffff; padding:20px; border:1px solid #e0e0e0; " bgcolor="#ffffff">
        <h2 style="color:#17b8ce; margin:0 0 5px 0; font-size:18px; font-family:Arial,Helvetica,sans-serif;">&#x1F4CA; &Eacute;volution sur les 4 derni&egrave;res semaines</h2>
        <p style="margin:0 0 10px 0; font-size:12px; color:#666666; text-align:center;">Volume re&ccedil;u (Go)</p>

        <!-- Legend -->
        <table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin-bottom:10px;">
        <tr>
            <td bgcolor="#b3e6ef" style="width:12px; height:12px;">&nbsp;</td>
            <td style="padding:0 15px 0 5px; font-size:11px; color:#666666;">3 sem. pr&eacute;c&eacute;dentes</td>
            <td bgcolor="#17b8ce" style="width:12px; height:12px;">&nbsp;</td>
            <td style="padding:0 0 0 5px; font-size:11px; color:#666666;">Semaine actuelle</td>
        </tr>
        </table>

        <!-- Bars (scrollable on narrow screens) -->
        <div style="overflow-x:auto; -webkit-overflow-scrolling:touch;">
        <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="min-width:560px; width:100%;">
        <tr valign="bottom" style="height:${CHART_HEIGHT}px;">
EOF

# Générer les barres du graphique
for i in {0..27}; do
    if [[ ${DAY_TOTALS[$i]} -gt 0 ]]; then
        bar_height=$(awk -v val="${DAY_TOTALS[$i]}" -v max="$MAX_VALUE" -v h="$CHART_HEIGHT" 'BEGIN {
            bh = int((val / max) * h)
            if (bh < 2) bh = 2
            printf "%d", bh
        }')
    else
        bar_height=1
    fi

    if [[ $i -ge 21 ]]; then
        color="#17b8ce"
    else
        color="#b3e6ef"
    fi

    value_gb=$(awk -v val="${DAY_TOTALS[$i]}" 'BEGIN {printf "%.2f", val / 1000000000}')

    echo "            <td align=\"center\" valign=\"bottom\" title=\"${DAY_LABELS[$i]} : ${value_gb} Go\" style=\"padding:0 2px;\">"
    echo "                <div style=\"background-color:${color}; border-bottom:${bar_height}px solid ${color}; width:16px; height:${bar_height}px; font-size:1px; line-height:${bar_height}px;\">&nbsp;</div>"
    echo "            </td>"
done

cat <<EOF
        </tr>
        <!-- X-axis labels -->
        <tr>
EOF

# Labels X tous les 2 jours
for i in {0..27}; do
    if (( i % 2 == 0 )); then
        label="${DAY_LABELS[$i]}"
    else
        label=""
    fi
    echo "            <td style=\"font-size:7px; color:#666666; text-align:center; padding-top:4px;\">${label}</td>"
done

cat <<EOF
        </tr>
        </table>
        </div>
    </td></tr>

    <!-- Spacer -->
    <tr><td style="padding:10px 0;"></td></tr>

    <!-- Top 10 table -->
    <tr><td style="background-color:#ffffff; padding:20px; border:1px solid #e0e0e0; " bgcolor="#ffffff">
        <h2 style="margin:0 0 15px 0; color:#17b8ce; font-size:18px; font-family:Arial,Helvetica,sans-serif; border-bottom:2px solid #17b8ce; padding-bottom:10px;">&#x1F3C6; Top 10 des consommations par machine</h2>
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;">
            <tr>
                <th width="50" bgcolor="#17b8ce" style="color:#ffffff; padding:12px; text-align:center; font-weight:600; font-size:14px;">#</th>
                <th bgcolor="#17b8ce" style="color:#ffffff; padding:12px; text-align:left; font-weight:600; font-size:14px;">Machine</th>
                <th bgcolor="#17b8ce" style="color:#ffffff; padding:12px; text-align:right; font-weight:600; font-size:14px;">Volume</th>
            </tr>
EOF

# Générer les lignes du top 10
rank=1
while IFS=$'\t' read -r hostname bytes; do
    if (( rank % 2 == 0 )); then
        row_bg="background-color:#f9f9f9;"
        row_bgcolor="bgcolor=\"#f9f9f9\""
    else
        row_bg=""
        row_bgcolor=""
    fi
    echo "            <tr style=\"${row_bg}\" ${row_bgcolor}>"
    echo "                <td style=\"padding:10px 12px; text-align:center; font-weight:bold; color:#17b8ce; border-bottom:1px solid #eeeeee; font-size:14px;\">$rank</td>"
    echo "                <td style=\"padding:10px 12px; border-bottom:1px solid #eeeeee; font-size:14px;\">$hostname</td>"
    echo "                <td style=\"padding:10px 12px; text-align:right; font-weight:600; border-bottom:1px solid #eeeeee; font-size:14px;\">$(format_bytes ${bytes:-0})</td>"
    echo "            </tr>"
    ((rank++))
done <<< "$TOP10"

cat <<EOF
        </table>
    </td></tr>

    <!-- Footer -->
    <tr><td style="text-align:center; color:#666666; padding:20px 0 0 0; border-top:1px solid #dddddd; font-size:13px;">
        <p style="margin:2px 0;">Ce rapport a &eacute;t&eacute; g&eacute;n&eacute;r&eacute; automatiquement par LogVault</p>
        <p style="margin:2px 0;">Pour plus d'informations, consultez <a href="https://www.logvault.io" style="color:#17b8ce; text-decoration:underline;" target="_blank">l'interface web LogVault</a></p>
    </td></tr>

</table>
<!-- End main content -->

</td></tr>
</table>
<!-- End outer wrapper -->

</body>
</html>
EOF

echo "Rapport généré avec succès!" >&2
