#!/bin/bash

# Download All Assets from NotebookLM - Videos + Audios

STORAGE_PATH="/home/ashraffarid2010/jadwaai.com/nlm_sessions/account_10/storage_state.json"
NOTEBOOK_ID="0f38d000-7497-442c-9b67-8773b02a558b"
OUTPUT_DIR="/home/ashraffarid2010/jadwaai.com/app/static/uploads/notebooks/35"
REPORT_ID="35"

echo "================================================================================"
echo "DOWNLOAD ALL ASSETS FROM NOTEBOOKLM"
echo "================================================================================"
echo "Storage: $STORAGE_PATH"
echo "Notebook ID: $NOTEBOOK_ID"
echo "Output Directory: $OUTPUT_DIR"
echo ""

# Ensure output directory exists
mkdir -p "$OUTPUT_DIR"

# Change to directory where we want to download
cd "$OUTPUT_DIR"

# Set NOTEBOOKLM_HOME and export it
export NOTEBOOKLM_HOME="$(dirname "$STORAGE_PATH")"

echo "Step 1: Setting notebook context..."
notebooklm --storage "$STORAGE_PATH" use "$NOTEBOOK_ID"

echo ""
echo "Step 2: Downloading all videos..."
echo "-----------------------------"
notebooklm --storage "$STORAGE_PATH" download video --all . --force

echo ""
echo "Step 3: Renaming video files..."
count=1
for video in *.mp4; do
    if [ -f "$video" ] && [[ ! "$video" =~ ^video_[0-9]+\.mp4$ ]]; then
        new_name="video_${count}.mp4"
        echo "Renaming: $video -> $new_name"
        mv "$video" "$new_name"
        count=$((count + 1))
    fi
done

echo ""
echo "Step 4: Downloading all audio files..."
echo "---------------------------------------"
notebooklm --storage "$STORAGE_PATH" download audio --all . --force

echo ""
echo "Step 5: Renaming audio files..."
count=1
for audio in *.mp3; do
    if [ -f "$audio" ] && [[ ! "$audio" =~ ^audio_[0-9]+\.mp3$ ]]; then
        new_name="audio_${count}.mp3"
        echo "Renaming: $audio -> $new_name"
        mv "$audio" "$new_name"
        count=$((count + 1))
    fi
done

echo ""
echo "Step 6: Final file listing..."
echo "Video files:"
ls -lah video_*.mp4 2>/dev/null || echo "No video files found"
echo ""
echo "Audio files:"
ls -lah audio_*.mp3 2>/dev/null || echo "No audio files found"

echo ""
echo "Step 7: Updating database..."
echo "-----------------------------"

# Update database for videos
for i in {1..3}; do
    video_file="video_${i}.mp4"
    if [ -f "$video_file" ]; then
        echo "Updating database for $video_file"
        python3 << EOF
import psycopg2
conn = psycopg2.connect(host="127.0.0.1", port=5432, database="jadwa", user="postgres")
cursor = conn.cursor()
cursor.execute("""
    UPDATE notebook_assets
    SET status = 'ready',
        file_path = 'uploads/notebooks/${REPORT_ID}/video_${i}.mp4',
        file_format = 'mp4',
        error_message = NULL,
        completed_at = NOW()
    WHERE report_id = ${REPORT_ID}
      AND asset_type = 'video'
      AND asset_index = ${i}
""")
conn.commit()
print(f"  ✅ Updated video_${i}")
cursor.close()
conn.close()
EOF
    fi
done

# Update database for additional audio files
for i in {2..3}; do
    audio_file="audio_${i}.mp3"
    if [ -f "$audio_file" ]; then
        echo "Updating database for $audio_file"
        python3 << EOF
import psycopg2
conn = psycopg2.connect(host="127.0.0.1", port=5432, database="jadwa", user="postgres")
cursor = conn.cursor()
cursor.execute("""
    UPDATE notebook_assets
    SET status = 'ready',
        file_path = 'uploads/notebooks/${REPORT_ID}/audio_${i}.mp3',
        file_format = 'mp3',
        error_message = NULL,
        completed_at = NOW()
    WHERE report_id = ${REPORT_ID}
      AND asset_type = 'audio'
      AND asset_index = ${i}
""")
conn.commit()
print(f"  ✅ Updated audio_${i}")
cursor.close()
conn.close()
EOF
    fi
done

echo ""
echo "================================================================================"
echo "✅ ALL ASSETS DOWNLOADED AND DATABASE UPDATED"
echo "================================================================================"
echo "Please refresh the Jadwa AI notebook page to see all assets!"
echo ""