#!/usr/bin/env bash
set -euo pipefail

# ────────────────────────────────────────────
# status_daemon.sh — Jarvis Daemon 状態確認
# ────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$SCRIPT_DIR/.daemon.pid"
LOG_DIR="$SCRIPT_DIR/logs"
TOKENS_JSONL="$LOG_DIR/tokens.jsonl"
EVENTS_JSONL="$LOG_DIR/events.jsonl"

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

# ── ヘッダ ────────────────────────────────────
echo ""
echo -e "${BOLD}════════ Jarvis Daemon ステータス ════════${RESET}"
echo -e "  $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# ── PID / 稼働確認 ────────────────────────────
if [[ -f "$PID_FILE" ]]; then
  PID=$(cat "$PID_FILE")
  if kill -0 "$PID" 2>/dev/null; then
    UPTIME=$(ps -o etime= -p "$PID" 2>/dev/null | tr -d ' ' || echo "不明")
    echo -e "  状態:    ${GREEN}${BOLD}● 稼働中${RESET}   (PID: $PID, 稼働時間: $UPTIME)"
  else
    echo -e "  状態:    ${RED}${BOLD}○ 停止中${RESET}   (PIDファイルあり・プロセスなし)"
  fi
else
  echo -e "  状態:    ${RED}${BOLD}○ 停止中${RESET}"
fi

echo ""

# ── Python でトークン/コスト集計 ─────────────
python3 - "$TOKENS_JSONL" "$EVENTS_JSONL" <<'PYEOF'
import sys, json, datetime, os

tokens_path = sys.argv[1]
events_path = sys.argv[2]

# ANSIカラー
R='\033[0;31m'; G='\033[0;32m'; Y='\033[1;33m'
C='\033[0;36m'; M='\033[0;35m'; B='\033[1m'; Z='\033[0m'

# config から上限値取得
MAX_PER_HOUR = 100_000
MAX_PER_DAY  = 1_000_000
try:
    import importlib.util, sys as _sys
    spec = importlib.util.spec_from_file_location(
        "config",
        os.path.join(os.path.dirname(tokens_path), "..", "config.py")
    )
    if spec and spec.loader:
        cfg = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(cfg)
        MAX_PER_HOUR = getattr(cfg, "MAX_TOKENS_PER_HOUR", MAX_PER_HOUR)
        MAX_PER_DAY  = getattr(cfg, "MAX_TOKENS_PER_DAY",  MAX_PER_DAY)
        INPUT_COST   = getattr(cfg, "INPUT_COST_PER_M",  3.0)
        OUTPUT_COST  = getattr(cfg, "OUTPUT_COST_PER_M", 15.0)
    else:
        INPUT_COST, OUTPUT_COST = 3.0, 15.0
except Exception:
    INPUT_COST, OUTPUT_COST = 3.0, 15.0

now = datetime.datetime.now(datetime.timezone.utc)
hour_ago = now - datetime.timedelta(hours=1)
day_ago  = now - datetime.timedelta(days=1)

def parse_tokens(path):
    records = []
    if not os.path.exists(path):
        return records
    with open(path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                r = json.loads(line)
                ts_str = r.get("timestamp", "")
                if ts_str:
                    ts = datetime.datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
                    r["_ts"] = ts
                    records.append(r)
            except Exception:
                pass
    return records

def sum_tokens(records, since):
    inp = out = cost = 0
    for r in records:
        if r.get("_ts", datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)) >= since:
            inp  += r.get("input_tokens", 0)
            out  += r.get("output_tokens", 0)
            cost += r.get("cost_usd", 0.0)
    return inp, out, cost

def pct_bar(value, maximum, width=20):
    pct = min(value / maximum, 1.0) if maximum > 0 else 0
    filled = int(pct * width)
    bar = "█" * filled + "░" * (width - filled)
    color = G if pct < 0.6 else (Y if pct < 0.85 else R)
    return f"{color}[{bar}]{Z} {pct*100:.1f}%"

recs = parse_tokens(tokens_path)
total_recs = len(recs)

# 集計
h_in, h_out, h_cost = sum_tokens(recs, hour_ago)
d_in, d_out, d_cost = sum_tokens(recs, day_ago)
t_in = sum(r.get("input_tokens", 0) for r in recs)
t_out = sum(r.get("output_tokens", 0) for r in recs)
t_cost = sum(r.get("cost_usd", 0.0) for r in recs)

print(f"  {B}── トークン消費 ─────────────────────────{Z}")
print(f"  {'':20}  {'入力':>10}  {'出力':>10}  {'合計':>12}  {'コスト(USD)':>12}")
print(f"  {'直近1時間':20}  {h_in:>10,}  {h_out:>10,}  {h_in+h_out:>12,}  ${h_cost:>11.4f}")
print(f"  {'直近24時間':20}  {d_in:>10,}  {d_out:>10,}  {d_in+d_out:>12,}  ${d_cost:>11.4f}")
print(f"  {'通算':20}  {t_in:>10,}  {t_out:>10,}  {t_in+t_out:>12,}  ${t_cost:>11.4f}")
print()
print(f"  {B}── 上限に対する使用率 ───────────────────{Z}")
print(f"  1時間上限 ({MAX_PER_HOUR:,}): {pct_bar(h_in+h_out, MAX_PER_HOUR)}")
print(f"  1日上限   ({MAX_PER_DAY:,}): {pct_bar(d_in+d_out, MAX_PER_DAY)}")
print()

# イベント集計
speak_h = speak_d = silent_h = silent_d = err_h = err_d = 0
if os.path.exists(events_path):
    with open(events_path) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                ev = json.loads(line)
                ts_str = ev.get("timestamp", "")
                if not ts_str:
                    continue
                ts = datetime.datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
                kind = ev.get("event", "")
                if kind == "speak":
                    if ts >= hour_ago: speak_h += 1
                    if ts >= day_ago:  speak_d += 1
                elif kind == "silent":
                    if ts >= hour_ago: silent_h += 1
                    if ts >= day_ago:  silent_d += 1
                elif kind == "error":
                    if ts >= hour_ago: err_h += 1
                    if ts >= day_ago:  err_d += 1
            except Exception:
                pass

print(f"  {B}── アクティビティ ───────────────────────{Z}")
print(f"  {'':30}  {'1時間':>6}  {'1日':>6}")
print(f"  {'発話（応答生成あり）':30}  {speak_h:>6}  {speak_d:>6}")
print(f"  {'静寂（発話なしスキップ）':30}  {silent_h:>6}  {silent_d:>6}")
errc = f"\033[0;31m{err_h:>6}\033[0m" if err_h > 0 else f"{err_h:>6}"
errd = f"\033[0;31m{err_d:>6}\033[0m" if err_d > 0 else f"{err_d:>6}"
print(f"  {'エラー':30}  {errc}  {errd}")
print(f"  {'総APIコール':30}  {total_recs:>6}")
PYEOF

echo ""
echo -e "${BOLD}══════════════════════════════════════════${RESET}"
echo ""
echo -e "  ログ監視: ${CYAN}./tail_logs.sh${RESET}"
echo -e "  停止:     ${CYAN}./stop_daemon.sh${RESET}"
echo ""
