#!/bin/bash
set -euo pipefail

# ============================================================
# cleanup-large-audio.sh
# 대용량 / 오래된 오디오 파일 정리 스크립트
#
# 삭제 조건 1: 오디오 파일(wav, mp3, m4a, ogg, flac, aac) 중 50MB 이상
# 삭제 조건 2: 오디오 파일 중 24시간 이상 경과 (크기 무관)
# 보호 조건  : task-timers.json 에서 status=running 인 task 경로는 스킵
# ============================================================

DRY_RUN=false
if [[ "${1:-}" == "--dry-run" ]]; then
    DRY_RUN=true
fi

SEARCH_DIRS=(
    "/home/jay/workspace"
    "/home/jay/projects"
)

TASK_TIMERS_JSON="/home/jay/workspace/memory/task-timers.json"
LOG_FILE="/home/jay/workspace/memory/logs/audio-cleanup.log"
SIZE_THRESHOLD_MB=50
AGE_THRESHOLD_HOURS=24

# 로그 디렉터리 보장
mkdir -p "$(dirname "$LOG_FILE")"

# ============================================================
# running 상태 task_id 목록 추출
# ============================================================
RUNNING_TASKS=()
if [[ -f "$TASK_TIMERS_JSON" ]]; then
    mapfile -t RUNNING_TASKS < <(
        python3 -c "
import json, sys
with open('$TASK_TIMERS_JSON') as f:
    data = json.load(f)
for tid, t in data.get('tasks', {}).items():
    if t.get('status') == 'running':
        print(tid)
" 2>/dev/null || true
    )
fi

# ============================================================
# 헬퍼 함수
# ============================================================

# 파일이 running task 경로에 속하는지 확인
is_protected() {
    local filepath="$1"
    for task_id in "${RUNNING_TASKS[@]:-}"; do
        if [[ -n "$task_id" && "$filepath" == *"$task_id"* ]]; then
            return 0  # 보호 대상
        fi
    done
    return 1
}

# 파일 크기(MB) 반환
get_size_mb() {
    local filepath="$1"
    du -m "$filepath" 2>/dev/null | awk '{print $1}'
}

# 파일 경과 시간(시간 단위) 반환
get_age_hours() {
    local filepath="$1"
    local now
    now=$(date +%s)
    local mtime
    mtime=$(stat -c %Y "$filepath" 2>/dev/null || echo "$now")
    echo $(( (now - mtime) / 3600 ))
}

# 로그 + 출력
log_action() {
    local action="$1"   # DELETED or DRY-RUN or SKIPPED
    local filepath="$2"
    local size_mb="$3"
    local age_h="$4"
    local timestamp
    timestamp=$(date "+%Y-%m-%d %H:%M:%S")
    local line="[$timestamp] $action: $filepath (${size_mb}MB, age: ${age_h}h)"
    echo "$line" | tee -a "$LOG_FILE"
}

# ============================================================
# 메인 처리
# ============================================================
deleted_count=0
skipped_count=0

echo "=== Audio Cleanup $(date '+%Y-%m-%d %H:%M:%S') ==="
echo "DRY_RUN: $DRY_RUN"
echo "Running (protected) tasks: ${RUNNING_TASKS[*]:-none}"
echo ""

# find 결과가 비어 있어도 오류 없이 처리하기 위해 while read 패턴 사용
while IFS= read -r -d '' filepath; do
    # 파일이 실제로 존재하는지 재확인 (find 이후 삭제됐을 수 있음)
    [[ -f "$filepath" ]] || continue

    size_mb=$(get_size_mb "$filepath")
    age_h=$(get_age_hours "$filepath")

    # 삭제 조건 판단
    meets_size=$(( size_mb >= SIZE_THRESHOLD_MB ))
    meets_age=$(( age_h >= AGE_THRESHOLD_HOURS ))

    if [[ $meets_size -eq 0 && $meets_age -eq 0 ]]; then
        continue  # 두 조건 모두 미충족 → 스킵
    fi

    # running task 보호
    if is_protected "$filepath"; then
        echo "[PROTECTED] $filepath (${size_mb}MB, age: ${age_h}h) — running task 경로, 스킵"
        (( skipped_count++ )) || true
        continue
    fi

    # 삭제 or dry-run
    if [[ "$DRY_RUN" == true ]]; then
        log_action "DRY-RUN" "$filepath" "$size_mb" "$age_h"
        (( deleted_count++ )) || true
    else
        log_action "DELETED" "$filepath" "$size_mb" "$age_h"
        rm -f "$filepath"
        (( deleted_count++ )) || true
    fi

done < <(
    # 검색 디렉터리별로 find 실행, 결과 합산
    for dir in "${SEARCH_DIRS[@]}"; do
        if [[ -d "$dir" ]]; then
            find "$dir" \
                \( -name "*.wav" -o -name "*.mp3" -o -name "*.m4a" -o -name "*.ogg" -o -name "*.flac" -o -name "*.aac" \) \
                -type f \
                -print0 2>/dev/null || true
        fi
    done
)

# ============================================================
# 결과 요약
# ============================================================
echo ""
echo "=== 실행 결과 요약 ==="
if [[ "$DRY_RUN" == true ]]; then
    echo "  모드      : DRY-RUN (실제 삭제 없음)"
    echo "  삭제 예정 : ${deleted_count}개 파일"
else
    echo "  모드      : 실제 삭제"
    echo "  삭제 완료 : ${deleted_count}개 파일"
fi
echo "  보호(스킵): ${skipped_count}개 파일"
echo "  로그 파일 : $LOG_FILE"
echo "======================"
