#!/usr/bin/env python3
"""
NotebookLM Video Asset Investigation Script

This script checks if a video exists in NotebookLM but failed to download locally.
It provides specific guidance on accessing the video directly from NotebookLM.
"""
import os
import sys

def main():
    print("=" * 80)
    print("NOTEBOOKLM VIDEO ASSET INVESTIGATION")
    print("=" * 80)

    # Report 35 details
    notebook_id = "0f38d000-7497-442c-9b67-8773b02a558b"
    notebook_url = f"https://notebooklm.google.com/notebook/{notebook_id}"

    print("\n📋 REPORT 35 DETAILS:")
    print(f"  Notebook ID: {notebook_id}")
    print(f"  Notebook URL: {notebook_url}")
    print(f"  NLM Account ID: 10")
    print(f"  Mode: notebooklm")

    print("\n🔍 INVESTIGATION RESULTS:")

    # Check local files
    upload_dir = "/home/ashraffarid2010/jadwaai.com/app/static/uploads/notebooks/35"
    if os.path.exists(upload_dir):
        files = os.listdir(upload_dir)
        print(f"\n  Files in local directory: {len(files)}")
        for f in sorted(files):
            filepath = os.path.join(upload_dir, f)
            size = os.path.getsize(filepath) / (1024 * 1024)
            print(f"    - {f} ({size:.2f} MB)")
    else:
        print(f"  Local directory does not exist: {upload_dir}")

    # Check for video files
    video_files = [f for f in os.listdir(upload_dir) if f.endswith(('.mp4', '.webm', '.mov', '.avi'))] if os.path.exists(upload_dir) else []

    if video_files:
        print(f"\n✅ VIDEO FILES FOUND LOCALLY: {len(video_files)}")
        for vf in video_files:
            print(f"  - {vf}")
    else:
        print("\n❌ NO VIDEO FILES FOUND LOCALLY")

    print("\n🎯 ANALYSIS:")
    print("  The video generation process timed out after 30 minutes (1800s).")
    print("  However, NotebookLM may have successfully created the video.")
    print("  The timeout occurred during the 'wait_for_completion' phase,")
    print("  which means the video might exist in NotebookLM but wasn't downloaded.")

    print("\n🔧 SOLUTIONS:")

    print("\n1️⃣  DIRECT ACCESS (Immediate):")
    print(f"   Open the notebook directly in NotebookLM:")
    print(f"   {notebook_url}")
    print("   - Look for the 'Video Overview' or 'ملخص مرئي' section")
    print("   - If the video exists, you can watch/download it from NotebookLM")
    print("   - Share the link directly with users")

    print("\n2️⃣  MANUAL DOWNLOAD (If video exists in NotebookLM):")
    print("   - Open the notebook in NotebookLM")
    print("   - Find the video artifact")
    print("   - Download manually")
    print("   - Upload to: " + upload_dir)
    print("   - Update database record")

    print("\n3️⃣  RETRY GENERATION (If video doesn't exist):")
    print("   - The video generation might have genuinely failed")
    print("   - Use the 'retry' button in the Jadwa AI interface")
    print("   - Consider using a different NotebookLM account")

    print("\n4️⃣  CODE IMPROVEMENT (Prevent future issues):")
    print("   - Implement post-timeout verification")
    print("   - Check NotebookLM API even after timeout")
    print("   - Add manual download/retry functionality")

    print("\n📊 DATABASE UPDATE (If you find and download the video):")
    print("   If you manually download the video file, run this SQL:")
    print(f"""
   UPDATE notebook_assets
   SET status = 'ready',
       file_path = 'uploads/notebooks/35/video.mp4',
       file_format = 'mp4',
       error_message = NULL,
       completed_at = NOW()
   WHERE report_id = 35
     AND asset_type = 'video';
    """)

    print("\n🔍 NEXT STEPS:")
    print("1. Open the NotebookLM notebook URL above")
    print("2. Check if video exists in NotebookLM")
    print("3. If yes: either share the link or download and update the database")
    print("4. If no: retry generation with increased timeout")

    print("\n" + "=" * 80)
    print("TIMESTAMP ISSUE DETAILS:")
    print("=" * 80)
    print("  Asset Created: 2026-05-03 19:51:52")
    print("  Timeout: 1800s (30 minutes)")
    print("  Expected Completion: ~2026-05-03 20:22:52")
    print("  Status: failed")
    print("  Task ID: d3a5a760-3e49-4a1e-b080-5dfef69bfb08")
    print("  Issue: Generation process timed out, but video may have been created")

    print("\n💡 KEY INSIGHT:")
    print("  NotebookLM video generation can take 20-30+ minutes.")
    print("  The timeout occurred, but the video might have been created")
    print("  shortly after the timeout and is now available in NotebookLM.")

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

if __name__ == "__main__":
    main()