#!/bin/bash
# migrate-seasons.sh — move old-format seasons clips into the new sky-cam
# directory structure for astronomical year 2025 only (Winter 2025-26 onward).
#
# Every *-final.mp4 clip is placed in the correct movement directory based on
# its YYYY-MM-DD filename date, regardless of how the old script labelled it.
# montage-mvt.sh re-adjusts speed for the whole movement anyway, so per-clip
# speed accuracy doesn't matter.
#
# Earlier years (Autumn 2025 / ASTRO_YEAR=2024 and before) are skipped.
#
# Usage:
#   ./migrate-seasons.sh [--dry-run] [OLD_ROOT]
#
#   --dry-run   print what would happen without moving anything
#   OLD_ROOT    root of old movie archive
#               (default: ~/drives/local-2tb/movies/sunrise)
#
# After running, trigger montages for completed movements:
#   ./montage-mvt.sh 2026-04-19 east   # Spring Mvt1 (~30/31 days)
#   ./montage-mvt.sh 2026-01-18 east   # Winter Mvt1 (~18/29 days)
#   ./montage-mvt.sh 2026-02-16 east   # Winter Mvt2 (~24/29 days)
#   ./montage-mvt.sh 2026-03-19 east   # Winter Mvt3 (~20/31 days)

set -euo pipefail

SCRIPT_DIR="$(dirname "$(realpath "$0")")"
source "$SCRIPT_DIR/sky-cam.conf"

DRY_RUN=false
OLD_ROOT="$HOME/drives/local-2tb/movies/sunrise"
CAM=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --dry-run)  DRY_RUN=true ;;
        --cam)      shift; CAM="$1" ;;
        --cam=*)    CAM="${1#--cam=}" ;;
        *)          OLD_ROOT="$1" ;;
    esac
    shift
done

[ -z "$CAM" ] && CAM="$SUNRISE_CAM"
NEW_ROOT="$MOVIES_DIR/$CAM/2025"

echo "Old archive : $OLD_ROOT"
echo "New root    : $NEW_ROOT"
echo "Camera      : $CAM"
$DRY_RUN && echo "(DRY RUN — no files will be moved)"
echo ""

declare -A CNT_MOVED CNT_SKIP

while IFS= read -r -d '' src; do
    fname="$(basename "$src")"

    # Extract YYYY-MM-DD prefix
    date_str="${fname%%_*}"
    if [[ ! "$date_str" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
        echo "SKIP (no date): $fname"
        continue
    fi

    # Classify date using the new system's boundaries
    if ! info="$(python3 "$SCRIPT_DIR/season_info.py" "$date_str" 2>/dev/null)"; then
        echo "ERROR: season_info.py failed for $date_str — skipping $fname"
        continue
    fi
    eval "$info"
    # Provides: SEASON  MVT_NUM  DAY_OF_MVT  DAYS_IN_MVT  ASTRO_YEAR  ...

    # Only process the current astronomical year
    if [ "$ASTRO_YEAR" != "2025" ]; then
        continue
    fi

    key="${SEASON}/Mvt${MVT_NUM}"
    dst="$NEW_ROOT/$SEASON/Mvt$MVT_NUM/$fname"

    if [ -e "$dst" ]; then
        printf "  EXISTS  %s\n" "$fname"
        CNT_SKIP["$key"]=$(( ${CNT_SKIP["$key"]:-0} + 1 ))
        continue
    fi

    if $DRY_RUN; then
        printf "  Day %2s/%-2s  %s  ->  %s/Mvt%s/\n" \
            "$DAY_OF_MVT" "$DAYS_IN_MVT" "$fname" "$SEASON" "$MVT_NUM"
    else
        mkdir -p "$(dirname "$dst")"
        mv "$src" "$dst"
    fi
    CNT_MOVED["$key"]=$(( ${CNT_MOVED["$key"]:-0} + 1 ))

done < <(find \
    "$OLD_ROOT/Spring" \
    "$OLD_ROOT/Summer" \
    "$OLD_ROOT/Winter" \
    "$OLD_ROOT/Autumn" \
    -name "*-final.mp4" -print0 2>/dev/null | sort -z)

echo ""
echo "=== Summary (ASTRO_YEAR=2025 only) ==="
printf "%-22s  %6s  %7s\n" "Movement" "Moved" "Skipped"
printf "%-22s  %6s  %7s\n" "--------" "-----" "-------"

declare -A ALL_KEYS
for k in "${!CNT_MOVED[@]}" "${!CNT_SKIP[@]}"; do ALL_KEYS["$k"]=1; done

total=0
for key in $(printf '%s\n' "${!ALL_KEYS[@]}" | sort); do
    m=${CNT_MOVED["$key"]:-0}
    s=${CNT_SKIP["$key"]:-0}
    printf "%-22s  %6d  %7d\n" "$key" "$m" "$s"
    total=$(( total + m ))
done
printf "%-22s  %6d\n" "TOTAL" "$total"

echo ""
$DRY_RUN && echo "Re-run without --dry-run to move the files." && echo ""

echo "Next steps:"
echo "  1. Build montages for completed movements:"
echo "       ./montage-mvt.sh 2026-04-19 $CAM   # Spring Mvt1 (today is last day)"
echo "       ./montage-mvt.sh 2026-01-18 $CAM   # Winter Mvt1"
echo "       ./montage-mvt.sh 2026-02-16 $CAM   # Winter Mvt2"
echo "       ./montage-mvt.sh 2026-03-19 $CAM   # Winter Mvt3"
echo "  2. Confirm each montage plays correctly with music."
echo "  3. Delete temp files from old archive:"
echo "       find \"$OLD_ROOT\" -name '*-temp.mp4' -delete"
