#!/usr/bin/env python3
"""
NotebookLM Video Download Retry Script

This script attempts to download a video from NotebookLM that may have
been created despite a timeout error during the initial generation.
"""
import os
import sys
import asyncio
from datetime import datetime

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

def main():
    print("=" * 80)
    print("NOTEBOOKLM VIDEO RETRY DOWNLOAD")
    print("=" * 80)

    report_id = 35
    notebook_id = "0f38d000-7497-442c-9b67-8773b02a558b"
    nlm_account_id = 10
    output_dir = f"/home/ashraffarid2010/jadwaai.com/app/static/uploads/notebooks/{report_id}"

    print(f"\n📋 Configuration:")
    print(f"  Report ID: {report_id}")
    print(f"  Notebook ID: {notebook_id}")
    print(f"  NLM Account ID: {nlm_account_id}")
    print(f"  Output Directory: {output_dir}")

    print(f"\n🔍 Step 1: Checking if video file already exists...")
    video_path = os.path.join(output_dir, "video.mp4")

    if os.path.exists(video_path):
        size = os.path.getsize(video_path) / (1024 * 1024)
        print(f"  ✅ Video file already exists: {size:.2f} MB")
        print(f"  Path: {video_path}")
        print("\n  The video may just need database updating. Run:")
        print(f"  UPDATE notebook_assets SET status = 'ready', file_path = 'uploads/notebooks/{report_id}/video.mp4', error_message = NULL WHERE report_id = {report_id} AND asset_type = 'video';")
        return

    print(f"  ❌ Video file not found locally")

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

    try:
        # Import after adding to path
        from app.ai.notebooklm_service import download_asset, run_sync

        async def try_download():
            """Try to download the video from NotebookLM."""
            try:
                file_path, file_format = await download_asset(
                    notebook_id=notebook_id,
                    asset_type="video",
                    output_path=os.path.join(output_dir, "video"),
                    admin_account_id=nlm_account_id
                )
                return file_path, file_format, None
            except Exception as e:
                return None, None, str(e)

        print("  Starting download attempt...")
        file_path, file_format, error = run_sync(try_download())

        if file_path and os.path.exists(file_path):
            size = os.path.getsize(file_path) / (1024 * 1024)
            print(f"  ✅ SUCCESS! Video downloaded: {size:.2f} MB")
            print(f"  Path: {file_path}")
            print(f"  Format: {file_format}")

            # Calculate relative path for database
            rel_path = os.path.relpath(file_path, "/home/ashraffarid2010/jadwaai.com/app/static")
            print(f"\n📊 Database Update Required:")
            print(f"  Run this SQL to update the database:")
            print(f"""
UPDATE notebook_assets
SET status = 'ready',
    file_path = '{rel_path}',
    file_format = '{file_format}',
    error_message = NULL,
    completed_at = NOW()
WHERE report_id = {report_id}
  AND asset_type = 'video';
            """)

        else:
            print(f"  ❌ Download failed: {error}")
            print(f"\n🔍 Step 3: Manual check required")
            print(f"  The video may not exist in NotebookLM yet.")
            print(f"  Notebook URL: https://notebooklm.google.com/notebook/{notebook_id}")
            print(f"\n  Options:")
            print(f"  1. Open the notebook URL above and check if video exists")
            print(f"  2. If exists, try downloading manually from NotebookLM")
            print(f"  3. If not exists, retry generation from Jadwa AI interface")

    except Exception as e:
        print(f"  ❌ Error during download attempt: {e}")
        print(f"\n  Manual intervention required.")
        print(f"  Notebook URL: https://notebooklm.google.com/notebook/{notebook_id}")

    print("\n" + "=" * 80)
    print("ADDITIONAL NOTES:")
    print("=" * 80)
    print("1. Video generation in NotebookLM can take 30+ minutes")
    print("2. The timeout (1800s) may have occurred before completion")
    print("3. If video exists in NotebookLM, it should be downloadable")
    print("4. If not, consider retrying generation during off-peak hours")
    print("5. Check NotebookLM account status and rate limits")

if __name__ == "__main__":
    main()