#!/usr/bin/env bash
# daily_activate.sh - 每天自动激活：读取日程文件 → 解析今日事项 → 创建提醒 → 发日报
#
# 由 setup.sh 注册为每日定时任务，无需用户手动触发。
#
# 依赖：
#   ~/.config/schedule-reminder/config.env  （由 setup.sh 写入）
#   python3, jq, openclaw

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${HOME}/.config/schedule-reminder/config.env"

# ── 读取配置 ──────────────────────────────────────────────
if [[ ! -f "$CONFIG_FILE" ]]; then
  echo "[schedule-reminder] 错误：配置文件不存在，请先运行 setup.sh" >&2
  exit 1
fi

# shellcheck source=/dev/null
source "$CONFIG_FILE"

# 必填变量检查
: "${SCHEDULE_FILE:?'请在 config.env 中设置 SCHEDULE_FILE'}"
: "${SCHEDULE_TZ:=Asia/Shanghai}"
: "${SCHEDULE_ADVANCE_MIN:=15}"
: "${SCHEDULE_DAILY_HOUR:=7}"
: "${SCHEDULE_DAILY_MIN:=0}"
: "${SCHEDULE_SEND_SUMMARY:=true}"
# SCHEDULE_CHANNEL / SCHEDULE_RECIPIENT 为可选，留空则 cron 默认回到上次对话渠道（channel=last）
SCHEDULE_CHANNEL="${SCHEDULE_CHANNEL:-}"
SCHEDULE_RECIPIENT="${SCHEDULE_RECIPIENT:-}"

TODAY=$(TZ="$SCHEDULE_TZ" date +%Y-%m-%d)
NOW=$(TZ="$SCHEDULE_TZ" date +"%Y-%m-%d %H:%M")
LOG_DIR="${HOME}/.config/schedule-reminder/logs"
mkdir -p "$LOG_DIR"
LOG_FILE="${LOG_DIR}/activate-${TODAY}.log"

log() { echo "[$(date '+%H:%M:%S')] $*" | tee -a "$LOG_FILE"; }

log "===== 日程提醒 每日激活 ====="
log "日期：$TODAY  渠道：${SCHEDULE_CHANNEL:-last}  接收者：${SCHEDULE_RECIPIENT:-(上次对话用户)}"

# ── 展开文件路径 ──────────────────────────────────────────
SCHEDULE_FILE_EXPANDED="${SCHEDULE_FILE/#\~/$HOME}"

if [[ ! -f "$SCHEDULE_FILE_EXPANDED" ]]; then
  MSG="⚠️ 日程文件未找到：${SCHEDULE_FILE}\n请检查文件路径是否正确。"
  SEND_CMD=(openclaw message send --message "$MSG")
  [[ -n "$SCHEDULE_CHANNEL" ]] && SEND_CMD+=(--channel "$SCHEDULE_CHANNEL")
  [[ -n "$SCHEDULE_RECIPIENT" ]] && SEND_CMD+=(--to "$SCHEDULE_RECIPIENT")
  "${SEND_CMD[@]}" 2>>"$LOG_FILE" || true
  log "错误：日程文件不存在：$SCHEDULE_FILE_EXPANDED"
  exit 1
fi

# ── 解析日程 ──────────────────────────────────────────────
PARSE_OUT="/tmp/schedule_parsed_${TODAY}.json"

python3 "${SCRIPT_DIR}/parse_schedule.py" \
  --file "$SCHEDULE_FILE_EXPANDED" \
  --mode today \
  --now "$NOW" \
  > "$PARSE_OUT" 2>>"$LOG_FILE"

UPCOMING_COUNT=$(jq '.summary.upcoming_count' "$PARSE_OUT")
CONFLICT_COUNT=$(jq '.summary.conflict_count' "$PARSE_OUT")

log "解析完成：today=$UPCOMING_COUNT 个事项，冲突=$CONFLICT_COUNT"

# ── 过滤掉「提醒时刻已过」的事项 ─────────────────────────
NOW_MIN=$(TZ="$SCHEDULE_TZ" date +%H:%M | awk -F: '{print $1*60+$2}')
FUTURE_EVENTS=$(jq --argjson now_min "$NOW_MIN" '
  .upcoming | map(select(
    (.remind_cron != null) and (.start_min != null) and (.start_min > $now_min)
  ))
' "$PARSE_OUT")

FUTURE_COUNT=$(echo "$FUTURE_EVENTS" | jq 'length')
log "有效（未过期）提醒事项：$FUTURE_COUNT 个"

# ── 构建今日日报消息 ──────────────────────────────────────
build_summary() {
  local date_cn
  date_cn=$(TZ="$SCHEDULE_TZ" date +"%m月%d日")

  local lines="📅 今日日程 · ${date_cn}\n\n"

  if [[ "$FUTURE_COUNT" -eq 0 && "$UPCOMING_COUNT" -eq 0 ]]; then
    lines+="今日没有日程安排，好好休息！\n"
  else
    # 有效提醒列表
    if [[ "$FUTURE_COUNT" -gt 0 ]]; then
      lines+="待提醒事项（共 ${FUTURE_COUNT} 个）：\n"
      while IFS= read -r ev; do
        local title start_str end_str location advance remind_str priority_icon
        title=$(echo "$ev" | jq -r '.title')
        start_str=$(echo "$ev" | jq -r '.start_str')
        end_str=$(echo "$ev" | jq -r '.end_str')
        location=$(echo "$ev" | jq -r '.location // ""')
        advance=$(echo "$ev" | jq -r '.advance_min')
        remind_str=$(echo "$ev" | jq -r '.remind_time_str // ""')
        local priority
        priority=$(echo "$ev" | jq -r '.priority')
        case "$priority" in
          高) priority_icon="🔴" ;;
          中) priority_icon="🟡" ;;
          低) priority_icon="⚪" ;;
          *) priority_icon="🔵" ;;
        esac

        lines+="  ${priority_icon} ${start_str}–${end_str} 【${title}】"
        [[ -n "$location" ]] && lines+=" @ ${location}"
        [[ -n "$remind_str" ]] && lines+="（⏰ ${remind_str} 提醒，提前${advance}分钟）"
        lines+="\n"
      done < <(echo "$FUTURE_EVENTS" | jq -c '.[]')
    fi

    # 已过期事项说明
    local expired_count
    expired_count=$(( UPCOMING_COUNT - FUTURE_COUNT ))
    if [[ "$expired_count" -gt 0 ]]; then
      lines+="\n（另有 ${expired_count} 个事项已开始或已结束，不再提醒）\n"
    fi
  fi

  # 冲突提示
  if [[ "$CONFLICT_COUNT" -gt 0 ]]; then
    lines+="\n⚠️ 检测到 ${CONFLICT_COUNT} 个时间冲突：\n"
    while IFS= read -r conflict; do
      local msg
      msg=$(echo "$conflict" | jq -r '.message')
      lines+="  ${msg}\n"
    done < <(jq -c '.conflicts[]' "$PARSE_OUT")
  fi

  lines+="\n祝今天顺利！"
  echo -e "$lines"
}

# ── 发送日报 ──────────────────────────────────────────────
if [[ "$SCHEDULE_SEND_SUMMARY" == "true" && "$UPCOMING_COUNT" -gt 0 ]]; then
  SUMMARY=$(build_summary)
  SEND_CMD=(openclaw message send --message "$SUMMARY")
  [[ -n "$SCHEDULE_CHANNEL" ]] && SEND_CMD+=(--channel "$SCHEDULE_CHANNEL")
  [[ -n "$SCHEDULE_RECIPIENT" ]] && SEND_CMD+=(--to "$SCHEDULE_RECIPIENT")
  "${SEND_CMD[@]}" 2>>"$LOG_FILE" && log "日报已发送" || log "日报发送失败"
elif [[ "$UPCOMING_COUNT" -eq 0 ]]; then
  log "今日无日程，跳过日报"
fi

# ── 创建今日提醒 cron 任务 ───────────────────────────────
if [[ "$FUTURE_COUNT" -gt 0 ]]; then
  # 将有效事项写入临时文件（按 create_reminders.sh 期望的结构）
  echo "$FUTURE_EVENTS" | jq '{
    meta: {},
    summary: { upcoming_count: length },
    upcoming: .
  }' > "/tmp/schedule_upcoming_${TODAY}.json"

  bash "${SCRIPT_DIR}/create_reminders.sh" \
    --events-json "/tmp/schedule_upcoming_${TODAY}.json" \
    --channel "$SCHEDULE_CHANNEL" \
    --to "$SCHEDULE_RECIPIENT" \
    --tz "$SCHEDULE_TZ" \
    2>>"$LOG_FILE" | tee -a "$LOG_FILE"

  log "提醒任务创建完成"
else
  log "无有效提醒事项，跳过创建"
fi

log "===== 激活完成 ====="
