#!/usr/bin/env python3
"""Download all book covers from Audiobookshelf"""

import asyncio
import sys
sys.path.insert(0, '.')
from app.database import async_session
from app.models import User, Book
from app.abs_client import get_abs_client
from app.main import download_cover_image
from sqlalchemy import select

async def download_all_covers():
    """Download covers for all books"""
    async with async_session() as db:
        # Get admin user
        result = await db.execute(select(User).where(User.is_admin == True))
        user = result.scalar_one()

        abs_client = get_abs_client(user)

        # Get all books
        result = await db.execute(select(Book))
        books = result.scalars().all()

        print(f"Found {len(books)} books to process")
        print("-" * 60)

        success_count = 0
        fail_count = 0

        for i, book in enumerate(books, 1):
            print(f"[{i}/{len(books)}] {book.title[:50]}")

            try:
                local_cover_url = await download_cover_image(abs_client, book.id)

                if local_cover_url:
                    book.cover_url = local_cover_url
                    print(f"  ✓ Downloaded: {local_cover_url}")
                    success_count += 1
                else:
                    print(f"  ✗ Failed to download")
                    fail_count += 1
            except Exception as e:
                print(f"  ✗ Error: {e}")
                fail_count += 1

        await db.commit()

        print()
        print("=" * 60)
        print(f"Downloaded: {success_count}")
        print(f"Failed: {fail_count}")
        print(f"Total: {len(books)}")

if __name__ == "__main__":
    print("Downloading all book covers...")
    print("=" * 60)
    asyncio.run(download_all_covers())
