#!/usr/bin/env python3
"""
Download Videos from NotebookLM

This script downloads all available videos from a NotebookLM notebook
and updates the database records.
"""
import os
import sys
import asyncio
from datetime import datetime

# Add app directory to path
sys.path.insert(0, '/home/ashraffarid2010/jadwaai.com')

def download_videos_from_notebooklm():
    """Download all videos from NotebookLM notebook."""
    notebook_id = "0f38d000-7497-442c-9b67-8773b02a558b"
    nlm_account_id = 10
    report_id = 35
    output_dir = f"/home/ashraffarid2010/jadwaai.com/app/static/uploads/notebooks/{report_id}"

    print("=" * 80)
    print("DOWNLOAD VIDEOS FROM NOTEBOOKLM")
    print("=" * 80)
    print(f"\n📋 Configuration:")
    print(f"  Notebook ID: {notebook_id}")
    print(f"  Report ID: {report_id}")
    print(f"  NLM Account ID: {nlm_account_id}")
    print(f"  Output Directory: {output_dir}")

    # Ensure output directory exists
    os.makedirs(output_dir, exist_ok=True)

    print(f"\n🔍 Step 1: Checking for existing video files...")
    existing_videos = []
    for i in range(1, 4):
        video_path = os.path.join(output_dir, f"video_{i}.mp4")
        if os.path.exists(video_path):
            size = os.path.getsize(video_path) / (1024 * 1024)
            existing_videos.append(i)
            print(f"  ✅ video_{i}.mp4 exists ({size:.2f} MB)")
        else:
            print(f"  ❌ video_{i}.mp4 not found")

    if existing_videos:
        print(f"\n  Found {len(existing_videos)} existing video(s)")
        print(f"  Skipping download for existing files")
    else:
        print(f"  No existing videos found")

    print(f"\n🔍 Step 2: Attempting to download videos from NotebookLM...")

    try:
        # Import NotebookLM service
        from app.ai.notebooklm_service import download_asset, run_sync

        async def download_all_videos():
            """Download all videos from NotebookLM."""
            downloaded_videos = []
            failed_videos = []

            for i in range(1, 4):
                if i in existing_videos:
                    print(f"\n  📹 video_{i}.mp4 already exists, skipping...")
                    downloaded_videos.append(i)
                    continue

                try:
                    print(f"\n  📹 Downloading video_{i}...")

                    output_path = os.path.join(output_dir, f"video_{i}")
                    file_path, file_format = await download_asset(
                        notebook_id=notebook_id,
                        asset_type="video",
                        output_path=output_path,
                        admin_account_id=nlm_account_id
                    )

                    if file_path and os.path.exists(file_path):
                        size = os.path.getsize(file_path) / (1024 * 1024)
                        print(f"    ✅ Downloaded: video_{i}.{file_format} ({size:.2f} MB)")
                        downloaded_videos.append(i)
                    else:
                        print(f"    ❌ Download failed - no file created")
                        failed_videos.append(i)

                except Exception as e:
                    print(f"    ❌ Error downloading video_{i}: {e}")
                    failed_videos.append(i)

            return downloaded_videos, failed_videos

        # Run the download process
        downloaded, failed = run_sync(download_all_videos())

        print(f"\n📊 DOWNLOAD SUMMARY:")
        print(f"  Successfully downloaded: {len(downloaded)} videos")
        print(f"  Failed: {len(failed)} videos")
        print(f"  Already existed: {len(existing_videos)} videos")

        total_ready = len(downloaded) + len(existing_videos)

        if downloaded:
            print(f"\n✅ DOWNLOADED VIDEOS:")
            for i in downloaded:
                video_path = os.path.join(output_dir, f"video_{i}.mp4")
                if os.path.exists(video_path):
                    size = os.path.getsize(video_path) / (1024 * 1024)
                    print(f"  video_{i}.mp4 ({size:.2f} MB)")

        if failed:
            print(f"\n❌ FAILED DOWNLOADS:")
            for i in failed:
                print(f"  video_{i} - try manually from NotebookLM")

        # Step 3: Update database
        if total_ready > 0:
            print(f"\n🔍 Step 3: Updating database records...")

            try:
                import psycopg2
                from psycopg2.extras import RealDictCursor

                conn = psycopg2.connect(
                    host="127.0.0.1",
                    port=5432,
                    database="jadwa",
                    user="postgres",
                )

                cursor = conn.cursor()

                # Update each successfully downloaded video
                for i in range(1, 4):
                    video_path = os.path.join(output_dir, f"video_{i}.mp4")

                    if os.path.exists(video_path):
                        rel_path = f"uploads/notebooks/{report_id}/video_{i}.mp4"

                        cursor.execute("""
                            UPDATE notebook_assets
                            SET status = 'ready',
                                file_path = %s,
                                file_format = 'mp4',
                                error_message = NULL,
                                completed_at = NOW()
                            WHERE report_id = %s
                              AND asset_type = 'video'
                              AND asset_index = %s
                        """, (rel_path, report_id, i))

                        print(f"  ✅ Updated database for video_{i}")

                conn.commit()
                cursor.close()
                conn.close()

                print(f"\n✅ DATABASE UPDATED SUCCESSFULLY")

            except Exception as e:
                print(f"❌ Error updating database: {e}")

        print(f"\n🎯 FINAL STATUS:")
        print(f"  Ready to use: {total_ready} videos")
        print(f"  Still pending: {3 - total_ready} videos")

        if total_ready == 3:
            print(f"\n🎉 ALL VIDEOS READY!")
            print(f"  Refresh the Jadwa AI page to see all videos with view/download buttons")
        elif total_ready > 0:
            print(f"\n✅ {total_ready} video(s) ready!")
            print(f"  Refresh the Jadwa AI page to see the available videos")
        else:
            print(f"\n⚠️  No videos could be downloaded automatically")
            print(f"  Please download manually from NotebookLM:")
            print(f"  https://notebooklm.google.com/notebook/{notebook_id}")

    except Exception as e:
        print(f"❌ Error during download process: {e}")
        import traceback
        traceback.print_exc()

        print(f"\n🔄 MANUAL DOWNLOAD INSTRUCTIONS:")
        print(f"1. Open: https://notebooklm.google.com/notebook/{notebook_id}")
        print(f"2. Find the 3 video files")
        print(f"3. Download each as video_1.mp4, video_2.mp4, video_3.mp4")
        print(f"4. Upload to: {output_dir}")
        print(f"5. Run SQL updates from DOWNLOAD_NOTEBOOKLM_VIDEOS.md")

    print("\n" + "=" * 80)

if __name__ == "__main__":
    download_videos_from_notebooklm()