#!/usr/bin/env bash
# AISieuRe Statusline — single-line minimal display

API_BASE="https://aisieure.com"
API_KEY="key_placeholder"

CACHE_DIR="${TMPDIR:-/tmp}/aisieure-statusline"
SESSION_BAL_FILE="$CACHE_DIR/session_start_bal.json"
CONTEXT_CACHE_FILE="$CACHE_DIR/context_cache.json"
CACHE_TTL=30

mkdir -p "$CACHE_DIR"

# ── Colors (256-color palette, synced with statusline.ps1) ──
ESC=$'\033'
CR="${ESC}[0m"
CB="${ESC}[1m"
DIM="${ESC}[2m"

# Foreground
FW="${ESC}[97m"         # Bright white
FG="${ESC}[32m"         # Green
FY="${ESC}[33m"         # Yellow
FR="${ESC}[31m"         # Red
FC="${ESC}[36m"         # Cyan
FM="${ESC}[35m"         # Magenta
FGR="${ESC}[38;5;242m"  # Neutral gray (borders)
FDG="${ESC}[38;5;238m"  # Dark gray (subtle)
FBG="${ESC}[92m"        # Bright green
FBC="${ESC}[96m"        # Bright cyan
FBY="${ESC}[93m"        # Bright yellow
FBR="${ESC}[91m"        # Bright red
FEM="${ESC}[38;5;48m"   # Emerald
FTL="${ESC}[38;5;117m"  # Teal / light blue
FLV="${ESC}[38;5;183m"  # Lavender
FOR="${ESC}[38;5;214m"  # Orange
FPK="${ESC}[38;5;211m"  # Pink
FSK="${ESC}[38;5;152m"  # Sky blue
FMN="${ESC}[38;5;158m"  # Mint

# ── Read stdin JSON ──
INPUT_JSON=""
[ ! -t 0 ] && INPUT_JSON=$(cat)

HAS_JQ=false
command -v jq &>/dev/null && HAS_JQ=true

json_val() {
  local json="$1" key="$2"
  if [ "$HAS_JQ" = true ]; then
    echo "$json" | jq -r ".$key // empty" 2>/dev/null
  else
    echo "$json" | grep -o "\"$key\"[[:space:]]*:[[:space:]]*[^,}]*" | head -1 | sed 's/.*:[[:space:]]*//' | tr -d '"' | tr -d ' '
  fi
}

json_nested() {
  local json="$1" path="$2"
  if [ "$HAS_JQ" = true ]; then
    echo "$json" | jq -r "$path // empty" 2>/dev/null
  else
    echo ""
  fi
}

# ── Format helpers ──
fmt_tokens() {
  local n=$1
  if [ "$n" -ge 1000000 ] 2>/dev/null; then
    printf "%.0fk" "$(echo "$n / 1000" | bc -l 2>/dev/null || echo 0)"
  elif [ "$n" -ge 1000 ] 2>/dev/null; then
    local k
    k=$(echo "scale=1; $n / 1000" | bc -l 2>/dev/null || echo "$((n / 1000))")
    echo "${k}k"
  else
    echo "$n"
  fi
}

fmt_tokens_short() {
  local n=$1
  if [ "$n" -ge 1000 ] 2>/dev/null; then
    echo "$((n / 1000))k"
  else
    echo "$n"
  fi
}

fmt_model() {
  local m="$1"
  [ -z "$m" ] && { echo "…"; return; }
  local tier=""
  echo "$m" | grep -qi "opus"   && tier="Opus"
  echo "$m" | grep -qi "sonnet" && tier="Sonnet"
  echo "$m" | grep -qi "haiku"  && tier="Haiku"
  if [ -n "$tier" ]; then
    local ver
    ver=$(echo "$m" | grep -oE '[0-9]+\.[0-9]+' | head -1)
    [ -z "$ver" ] && ver=$(echo "$m" | grep -oE '[0-9]+-[0-9]+' | head -1 | tr '-' '.')
    [ -n "$ver" ] && echo "${tier} ${ver}" || echo "$tier"
  else
    local s
    s=$(echo "$m" | sed 's/^claude-//' | sed 's/-[0-9]*$//')
    [ -z "$s" ] && { echo "…"; return; }
    echo "${s:0:14}"
  fi
}

fmt_credits() {
  local n="$1"
  if [ "$(echo "$n >= 10" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null; then
    printf "%.1f" "$n"
  elif [ "$(echo "$n >= 1" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null; then
    printf "%.2f" "$n"
  elif [ "$(echo "$n >= 0.01" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null; then
    printf "%.3f" "$n"
  else
    printf "%.2f" "$n"
  fi
}

# ── Parse context ──
MODEL="" MODEL_ID="" CTX_TOKENS=0 INPUT_TOKENS=0 OUTPUT_TOKENS=0 MAX_TOKENS=200000
LINES_ADD=0 LINES_DEL=0

if [ -n "$INPUT_JSON" ]; then
  MODEL=$(json_nested "$INPUT_JSON" ".model.display_name")
  MODEL_ID=$(json_nested "$INPUT_JSON" ".model.id")

  INPUT_TOKENS=$(json_nested "$INPUT_JSON" ".context_window.current_usage.input_tokens")
  local_cc=$(json_nested "$INPUT_JSON" ".context_window.current_usage.cache_creation_input_tokens")
  local_cr=$(json_nested "$INPUT_JSON" ".context_window.current_usage.cache_read_input_tokens")
  OUTPUT_TOKENS=$(json_nested "$INPUT_JSON" ".context_window.current_usage.output_tokens")
  INPUT_TOKENS=${INPUT_TOKENS:-0}; local_cc=${local_cc:-0}; local_cr=${local_cr:-0}; OUTPUT_TOKENS=${OUTPUT_TOKENS:-0}
  total_ctx=$((INPUT_TOKENS + local_cc + local_cr + OUTPUT_TOKENS))

  ctx_max=$(json_nested "$INPUT_JSON" ".context_window.context_window_size")
  [ -n "$ctx_max" ] && [ "$ctx_max" != "null" ] && [ "$ctx_max" -gt 0 ] 2>/dev/null && MAX_TOKENS=$ctx_max

  if [ "$total_ctx" -gt 0 ]; then
    CTX_TOKENS=$total_ctx
    echo "{\"ctx\":$total_ctx,\"inp\":$INPUT_TOKENS,\"out\":$OUTPUT_TOKENS,\"max\":$MAX_TOKENS}" > "$CONTEXT_CACHE_FILE" 2>/dev/null || true
  elif [ -f "$CONTEXT_CACHE_FILE" ]; then
    cache_age=$(( $(date +%s) - $(stat -c %Y "$CONTEXT_CACHE_FILE" 2>/dev/null || stat -f %m "$CONTEXT_CACHE_FILE" 2>/dev/null || echo 0) ))
    if [ "$cache_age" -lt "$CACHE_TTL" ]; then
      CTX_TOKENS=$(json_val "$(cat "$CONTEXT_CACHE_FILE")" "ctx")
      INPUT_TOKENS=$(json_val "$(cat "$CONTEXT_CACHE_FILE")" "inp")
      OUTPUT_TOKENS=$(json_val "$(cat "$CONTEXT_CACHE_FILE")" "out")
      MAX_TOKENS=$(json_val "$(cat "$CONTEXT_CACHE_FILE")" "max")
      CTX_TOKENS=${CTX_TOKENS:-0}; INPUT_TOKENS=${INPUT_TOKENS:-0}; OUTPUT_TOKENS=${OUTPUT_TOKENS:-0}; MAX_TOKENS=${MAX_TOKENS:-200000}
    fi
  fi

  LINES_ADD=$(json_nested "$INPUT_JSON" ".cost.total_lines_added")
  LINES_DEL=$(json_nested "$INPUT_JSON" ".cost.total_lines_removed")
  LINES_ADD=${LINES_ADD:-0}; LINES_DEL=${LINES_DEL:-0}
fi

# ── Fetch balance (cached) ──
get_balance() {
  local url="$API_BASE/v1/balance"
  if [ -n "$MODEL_ID" ]; then
    url="${url}?model=$(printf '%s' "$MODEL_ID" | sed 's/ /%20/g')"
  fi
  local ckey
  ckey=$(echo "${MODEL_ID:-_}" | sed 's/[^a-zA-Z0-9._-]/_/g')
  local bfile="$CACHE_DIR/bal_${ckey}.json"

  if [ -f "$bfile" ]; then
    local age=$(( $(date +%s) - $(stat -c %Y "$bfile" 2>/dev/null || stat -f %m "$bfile" 2>/dev/null || echo 0) ))
    [ "$age" -lt "$CACHE_TTL" ] && { cat "$bfile"; return; }
  fi

  local resp
  if resp=$(curl -fsSL --connect-timeout 3 -H "Authorization: Bearer $API_KEY" "$url" 2>/dev/null); then
    echo "$resp" > "$bfile" 2>/dev/null || true
    echo "$resp"; return
  fi
  [ -f "$bfile" ] && cat "$bfile"
}

# ── Main ──
# Layout: ✦ Opus 4.6 - 18.8k/200k 9% - ⚡0.00/400 - (in:18k out:57)
main() {
  local bal_data
  bal_data=$(get_balance)

  local eff_max=$MAX_TOKENS
  if [ -n "$bal_data" ]; then
    local api_max
    api_max=$(json_nested "$bal_data" ".model_limits.max_context_tokens")
    [ -n "$api_max" ] && [ "$api_max" -gt 0 ] 2>/dev/null && eff_max=$api_max
  fi

  local ctx_pct=0
  [ "$eff_max" -gt 0 ] 2>/dev/null && ctx_pct=$(( CTX_TOKENS * 100 / eff_max ))

  # Context color
  local pct_color="$FBG"
  [ "$ctx_pct" -ge 50 ] 2>/dev/null && pct_color="$FBY"
  [ "$ctx_pct" -ge 70 ] 2>/dev/null && pct_color="$FOR"
  [ "$ctx_pct" -ge 85 ] 2>/dev/null && pct_color="$FBR"

  # Model name + color
  local mdl
  mdl=$(fmt_model "$MODEL")
  local mdl_color="$FLV"
  echo "$mdl" | grep -qi "opus"   && mdl_color="$FOR"
  echo "$mdl" | grep -qi "sonnet" && mdl_color="$FTL"
  echo "$mdl" | grep -qi "haiku"  && mdl_color="$FMN"

  local D=" ${FDG}-${CR} "

  # Build: ✦ Opus 4.6 - 18.8k/200k 9% - ⚡0.00/400 - (in:18k out:57)
  local line="${FEM}✦${CR} ${mdl_color}${CB}${mdl}${CR}"
  line+="${D}${pct_color}${CB}$(fmt_tokens "$CTX_TOKENS")${CR}${FGR}/$(fmt_tokens_short "$eff_max")${CR} ${pct_color}${ctx_pct}%${CR}"

  # Credits: ⚡session/remain
  if [ -n "$bal_data" ]; then
    local cur_remain
    cur_remain=$(json_val "$bal_data" "remaining_credits")
    cur_remain=${cur_remain:-0}

    # Session tracking
    local sess_used="0"
    if [ -f "$SESSION_BAL_FILE" ]; then
      local sess_age=$(( $(date +%s) - $(stat -c %Y "$SESSION_BAL_FILE" 2>/dev/null || stat -f %m "$SESSION_BAL_FILE" 2>/dev/null || echo 0) ))
      if [ "$sess_age" -lt 21600 ]; then
        local saved
        saved=$(json_val "$(cat "$SESSION_BAL_FILE")" "r")
        saved=${saved:-0}
        if [ "$(echo "$saved >= $cur_remain" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null; then
          sess_used=$(echo "$saved - $cur_remain" | bc -l 2>/dev/null || echo "0")
        else
          echo "{\"r\":$cur_remain}" > "$SESSION_BAL_FILE" 2>/dev/null || true
        fi
      else
        echo "{\"r\":$cur_remain}" > "$SESSION_BAL_FILE" 2>/dev/null || true
      fi
    else
      echo "{\"r\":$cur_remain}" > "$SESSION_BAL_FILE" 2>/dev/null || true
    fi
    [ "$(echo "$sess_used < 0" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null && sess_used="0"

    local sess_fmt
    sess_fmt=$(fmt_credits "$sess_used")

    # Session credits color
    local sess_color="$FGR"
    [ "$(echo "$sess_used >= 10" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null && sess_color="$FBY"
    [ "$(echo "$sess_used >= 50" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null && sess_color="$FBR"

    local pkg_type
    pkg_type=$(json_val "$bal_data" "package_type")
    local total_cr remaining_cr
    total_cr=$(json_val "$bal_data" "total_credits")
    remaining_cr=$(json_val "$bal_data" "remaining_credits")

    if [ "$pkg_type" = "unlimited" ]; then
      line+="${D}${sess_color}⚡${sess_fmt}${CR} ${FBG}∞${CR}"
    elif [ -n "$total_cr" ] && [ "$total_cr" != "0" ]; then
      local r_ratio
      r_ratio=$(echo "$remaining_cr / $total_cr" | bc -l 2>/dev/null || echo "1")
      local bcol="$FBG"
      [ "$(echo "$r_ratio <= 0.3" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null && bcol="$FBY"
      [ "$(echo "$r_ratio <= 0.1" | bc -l 2>/dev/null || echo 0)" = "1" ] 2>/dev/null && bcol="$FBR"

      local rint
      rint=$(printf "%.0f" "$remaining_cr" 2>/dev/null || echo "$remaining_cr")

      line+="${D}${sess_color}⚡${sess_fmt}${CR}${FGR}/${CR}${bcol}${rint}${CR}"
    else
      line+="${D}${sess_color}⚡${sess_fmt}${CR}"
    fi
  fi

  # In/Out
  if [ "$INPUT_TOKENS" -gt 0 ] 2>/dev/null || [ "$OUTPUT_TOKENS" -gt 0 ] 2>/dev/null; then
    line+="${D}${FDG}(${FSK}in:$(fmt_tokens_short "$INPUT_TOKENS")${CR} ${FPK}out:$(fmt_tokens_short "$OUTPUT_TOKENS")${FDG})${CR}"
  fi

  echo -e "$line"
}

main
