#!/bin/bash
# 海外中国投资项目分析简报 - 月报生成脚本
# 执行时间：每月 1 日 09:00

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(dirname "$SCRIPT_DIR")"
REPORT_DIR="/home/admin/.openclaw/workspace/reports/overseas_briefing"
MONTHLY_DIR="$REPORT_DIR/monthly"
LOG_FILE="$REPORT_DIR/cron.log"

mkdir -p "$MONTHLY_DIR"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 开始生成月报" >> "$LOG_FILE"

# 日期变量
TODAY=$(date '+%Y-%m-%d')
LAST_MONTH=$(date -d 'last month' '+%Y-%m')
MONTH_START=$(date -d 'last month' '+%Y-%m-01')
MONTH_END=$(date -d 'last day of last month' '+%Y-%m-%d')

# 生成月报
python3 "$SCRIPT_DIR/generate_briefing.py" \
  --input "$REPORT_DIR/raw/" \
  --output "$MONTHLY_DIR/monthly_${LAST_MONTH}.md" \
  --type monthly \
  --period-start "$MONTH_START" \
  --period-end "$MONTH_END" 2>> "$LOG_FILE"

# 转换为 PDF
if command -v pandoc &> /dev/null; then
  pandoc "$MONTHLY_DIR/monthly_${LAST_MONTH}.md" \
    --output "$MONTHLY_DIR/monthly_${LAST_MONTH}.pdf" \
    --template "$SKILL_DIR/templates/govdoc.tex" 2>> "$LOG_FILE" || true
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 月报生成完成" >> "$LOG_FILE"
echo "" >> "$LOG_FILE"
