"""
Starts the Book Catalog Gallery web app.
Usage: python run.py
"""
import sqlite3
import subprocess
import sys
import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))

def ensure_description_column():
    """Add app-managed columns to book_images if they don't exist yet."""
    conn = sqlite3.connect("books.db")
    cols = [r[1] for r in conn.execute("PRAGMA table_info(book_images)").fetchall()]
    if "description" not in cols:
        conn.execute('ALTER TABLE book_images ADD COLUMN description TEXT DEFAULT ""')
        print("Added 'description' column to book_images table.")
    if "review_status" not in cols:
        conn.execute("ALTER TABLE book_images ADD COLUMN review_status TEXT DEFAULT 'pending'")
        print("Added 'review_status' column to book_images table.")
    if "review_updated_at" not in cols:
        conn.execute('ALTER TABLE book_images ADD COLUMN review_updated_at TEXT DEFAULT ""')
        print("Added 'review_updated_at' column to book_images table.")
    if "image_url" not in cols:
        conn.execute('ALTER TABLE book_images ADD COLUMN image_url TEXT DEFAULT ""')
        print("Added 'image_url' column to book_images table.")
    if "thumb_url" not in cols:
        conn.execute('ALTER TABLE book_images ADD COLUMN thumb_url TEXT DEFAULT ""')
        print("Added 'thumb_url' column to book_images table.")
    if "storage_path" not in cols:
        conn.execute('ALTER TABLE book_images ADD COLUMN storage_path TEXT DEFAULT ""')
        print("Added 'storage_path' column to book_images table.")
    if "thumb_storage_path" not in cols:
        conn.execute('ALTER TABLE book_images ADD COLUMN thumb_storage_path TEXT DEFAULT ""')
        print("Added 'thumb_storage_path' column to book_images table.")
    conn.execute("UPDATE book_images SET review_status = 'pending' WHERE review_status IS NULL OR TRIM(review_status) = ''")
    conn.commit()
    count = conn.execute("SELECT COUNT(*) FROM book_images").fetchone()[0]
    conn.close()
    return count

def main():
    count = ensure_description_column()
    print(f"Database has {count} book images ready.")
    print(f"\nStarting web app on http://127.0.0.1:8000")
    print("Press Ctrl+C to stop.\n")
    subprocess.run([
        sys.executable, "-m", "uvicorn",
        "app.main:app",
        "--host", "127.0.0.1",
        "--port", "8000",
        "--reload"
    ])

if __name__ == "__main__":
    main()
