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

This script uses the notebooklm CLI to download videos directly.
"""
import os
import sys
import subprocess
import shutil
from datetime import datetime

def download_videos_using_cli():
    """Download videos using notebooklm CLI."""
    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}"
    admin_session = f"/home/ashraffarid2010/jadwaai.com/nlm_sessions/account_{nlm_account_id}/storage_state.json"

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

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

    print(f"\n🔍 Step 1: Checking notebooklm CLI availability...")
    if not shutil.which("notebooklm"):
        print("  ❌ notebooklm CLI not found")
        print("  Installing notebooklm...")
        try:
            subprocess.run(["pip", "install", "notebooklm-py"], check=True)
            print("  ✅ notebooklm-py installed")
        except Exception as e:
            print(f"  ❌ Could not install notebooklm-py: {e}")
            return manual_fallback(notebook_id, output_dir)
    else:
        print("  ✅ notebooklm CLI found")

    print(f"\n🔍 Step 2: Checking admin session...")
    if not os.path.exists(admin_session):
        print(f"  ❌ Admin session not found: {admin_session}")
        return manual_fallback(notebook_id, output_dir)
    else:
        print(f"  ✅ Admin session found")

    print(f"\n🔍 Step 3: Setting up environment...")
    session_dir = os.path.dirname(admin_session)
    env = os.environ.copy()
    env["NOTEBOOKLM_HOME"] = session_dir

    print(f"  NOTEBOOKLM_HOME = {session_dir}")

    print(f"\n🔍 Step 4: Downloading videos...")

    downloaded_videos = []

    for i in range(1, 4):
        video_path = os.path.join(output_dir, f"video_{i}.mp4")

        # Check if already exists
        if os.path.exists(video_path):
            size = os.path.getsize(video_path) / (1024 * 1024)
            print(f"\n  📹 video_{i}.mp4 already exists ({size:.2f} MB)")
            downloaded_videos.append(i)
            continue

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

        try:
            # Try to download using notebooklm CLI
            output_file = os.path.join(output_dir, f"video_{i}.mp4")

            result = subprocess.run([
                "notebooklm",
                "--storage", admin_session,
                "download",
                "video",
                "-n", notebook_id,
                "-a", str(i),  # Artifact number
                output_file
            ], env=env, capture_output=True, text=True, timeout=300)

            if result.returncode == 0:
                # Check if file was created
                if os.path.exists(video_path):
                    size = os.path.getsize(video_path) / (1024 * 1024)
                    print(f"    ✅ Downloaded: video_{i}.mp4 ({size:.2f} MB)")
                    downloaded_videos.append(i)
                else:
                    print(f"    ⚠️  Download command succeeded but file not found")
                    print(f"    Output: {result.stdout}")
            else:
                print(f"    ❌ Download failed")
                print(f"    Error: {result.stderr}")
                print(f"    Output: {result.stdout}")

        except subprocess.TimeoutExpired:
            print(f"    ❌ Download timed out (5 minutes)")
        except Exception as e:
            print(f"    ❌ Error: {e}")

    # Step 5: Update database
    if downloaded_videos:
        print(f"\n🔍 Step 5: Updating database...")

        try:
            import psycopg2

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

            cursor = conn.cursor()

            for i in downloaded_videos:
                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✅ SUCCESSFULLY UPDATED {len(downloaded_videos)} VIDEO(S)")

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

        print(f"\n🎯 RESULT:")
        print(f"  Ready: {len(downloaded_videos)}/3 videos")
        print(f"  Refresh Jadwa AI page to see videos")

        if len(downloaded_videos) == 3:
            print(f"\n🎉 ALL 3 VIDEOS SUCCESSFULLY DOWNLOADED!")
        else:
            remaining = 3 - len(downloaded_videos)
            print(f"\n⚠️  {remaining} video(s) still need manual download")

    else:
        print(f"\n❌ No videos could be downloaded automatically")
        return manual_fallback(notebook_id, output_dir)

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

def manual_fallback(notebook_id, output_dir):
    """Provide manual download instructions."""
    print(f"\n🔄 MANUAL DOWNLOAD REQUIRED")
    print(f"=" * 80)
    print(f"1. Open NotebookLM:")
    print(f"   https://notebooklm.google.com/notebook/{notebook_id}")
    print(f"\n2. Download each video:")
    print(f"   - Find 'Video Overview' or 'ملخص مرئي' section")
    print(f"   - Download each of the 3 videos")
    print(f"   - Save as: video_1.mp4, video_2.mp4, video_3.mp4")
    print(f"\n3. Upload to server:")
    print(f"   scp video_*.mp4 user@server:{output_dir}/")
    print(f"\n4. Update database (see DOWNLOAD_NOTEBOOKLM_VIDEOS.md)")
    print(f"\n" + "=" * 80)

if __name__ == "__main__":
    download_videos_using_cli()