#!/usr/bin/env bash

# ============================================
# Date Formats
# ============================================

FMT_DATE_ISO="%Y-%m-%d"           # 2026-05-10
FMT_DATE_EU="%d/%m/%Y"            # 10/05/2026
FMT_DATE_EU_DASH="%d-%m-%Y"       # 10-05-2026
FMT_DATETIME_ISO="%Y-%m-%d %H:%M" # 2026-05-10 22:39
FMT_DATETIME_EU="%d/%m/%Y %H:%M"  # 10/05/2026 22:39

# Default — can be overridden in wgctl.conf
FMT_DATE="${FMT_DATE_ISO}"
FMT_DATETIME="${FMT_DATETIME_ISO}"
FMT_DATETIME_SHORT="%m-%d %H:%M"

# Load from config or use default
_FMT_DATE_FORMAT="${DATE_FORMAT:-iso}"

FMT_HELPER="${_CTX_ROOT}/core/fmt_helper.py"

function fmt::date() {
  local ts="$1"
  date -d "@${ts}" "+${FMT_DATE}" 2>/dev/null || echo "$ts"
}

function fmt::datetime() {
  local ts="$1"
  date -d "@${ts}" "+${FMT_DATETIME}" 2>/dev/null || echo "$ts"
}

function fmt::datetime_iso() {
  local iso="$1"
  python3 "$FMT_HELPER" fmt_datetime "$iso" "$FMT_DATETIME" </dev/null
}

# fmt::datetime_short <unix_timestamp>
# Returns a compact datetime — just time if today, short date+time if older.
# Respects configured date format. Returns "—" for empty/zero timestamps.
function fmt::datetime_short() {
  local ts="${1:-}"
  [[ -z "$ts" || "$ts" == "0" ]] && echo "—" && return 0
 
  local today ts_day
  today=$(date +%Y-%m-%d)
  ts_day=$(date -d "@${ts}" +%Y-%m-%d 2>/dev/null) || { echo "—"; return 0; }
 
  if [[ "$ts_day" == "$today" ]]; then
    date -d "@${ts}" +"%H:%M" 2>/dev/null || echo "—"
  else
    case "$_FMT_DATE_FORMAT" in
      iso)  date -d "@${ts}" +"%m-%d %H:%M" 2>/dev/null || echo "—" ;;
      eu*)  date -d "@${ts}" +"%d/%m %H:%M" 2>/dev/null || echo "—" ;;
      *)    date -d "@${ts}" +"%m-%d %H:%M" 2>/dev/null || echo "—" ;;
    esac
  fi
}

function fmt::set_date_format() {
  local format="$1"
  case "$format" in
    iso)
      FMT_DATE="%Y-%m-%d"
      FMT_DATETIME="%Y-%m-%d %H:%M"
      FMT_DATETIME_SHORT="%m-%d %H:%M"
      ;;
    eu)
      FMT_DATE="%d/%m/%Y"
      FMT_DATETIME="%d/%m/%Y %H:%M"
      FMT_DATETIME_SHORT="%d/%m %H:%M"
      ;;
    eu-dash)
      FMT_DATE="%d-%m-%Y"
      FMT_DATETIME="%d-%m-%Y %H:%M"
      FMT_DATETIME_SHORT="%d-%m %H:%M"
      ;;
    *) log::error "Unknown date format: $format" ;;
  esac
}

function fmt::bytes() {
  local bytes="${1:-0}"
  if (( bytes == 0 )); then
    printf "—"
  elif (( bytes >= 1073741824 )); then
    printf "%dGB" $(( bytes / 1073741824 ))
  elif (( bytes >= 1048576 )); then
    printf "%dMB" $(( bytes / 1048576 ))
  elif (( bytes >= 1024 )); then
    printf "%dKB" $(( bytes / 1024 ))
  else
    printf "%dB" "$bytes"
  fi
}