import json
import os
import logging
from pymongo import MongoClient

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Connect to MongoDB
client = MongoClient('mongodb+srv://dbUser:Rmit1234_@cluster0.uyfgear.mongodb.net/?appName=Cluster0')
db = client['wiki']
logger.info("Connected to MongoDB")


# Migrate books_queue.json
base_dir = os.path.dirname(os.path.abspath(__file__))
book_queue = os.path.join(base_dir, 'books_queue.json')
cache_dir = os.path.join(base_dir, 'book_cache')

with open(book_queue, 'r', encoding='utf-8') as f:
    queue_data = json.load(f)
logger.info(f"Loaded {len(queue_data['books'])} books from queue")


for book in queue_data['books']:
    if book.get('status') == 'done':
        path = os.path.join(cache_dir, book['book_url'].split('/')[-1] + '.json')
        with open(path, 'r', encoding='utf-8') as f:
            cache_data = json.load(f)
        
        logger.info(f"Backup book: {book.get('book_url', 'Unknown')}")
        result = db.book_info.update_one({'book_url': book['book_url']}, {'$set': book}, upsert=True)
        if result.upserted_id:
            book_id = result.upserted_id
            logger.info(f"Inserted book_info with ID: {book_id}")
        else:
            book_id = db.book_info.find_one({'book_url': book['book_url']})['_id']
            logger.info(f"Updated book_info with ID: {book_id}")


        chapters = db.book_chapters.update_one({'book_id': book_id}, {'$set': cache_data}, upsert=True)
        if chapters.upserted_id:
            logger.info(f"Inserted book_chapters with ID: {chapters.upserted_id}")
        else:
            logger.info(f"Updated book_chapters for book_id: {book_id}")

logger.info("Migration complete!")