from motor.motor_asyncio import AsyncIOMotorClient
from app.entities.search_response import SearchResponse,NewsResponse
from typing import List
from app.core.dependencies import pydantic_to_mongo_dict
from app.core.config import settings


class NewsRepository:
    def __init__(self, mongo_url: str, db_name: str):
        self.client = AsyncIOMotorClient(mongo_url)
        self.db = self.client[db_name]
        self.collection = self.db["search_response"]

    async def save_news_batch(self, news_items: List[SearchResponse]):
        """Save multiple news items in bulk"""
        try:
            # Convert all items to dicts
            news_dicts = []
            for item in news_items:
                news_dict = pydantic_to_mongo_dict(item)
                news_dict["_id"] = str(item.id)  # ✅ Use UUID as Mongo _id
                news_dicts.append(news_dict)
            
            # Use ordered=False to continue inserting even if some fail
            result = await self.collection.insert_many(news_dicts, ordered=False)
            return [res for res in news_dicts]
            
        except Exception as e:
            raise e
            # logger.error(f"Bulk insert error: {e}")
            # If bulk insert fails, try individual inserts
            # return await self._fallback_individual_inserts(news_items)
    
    async def list_news_batch(self):
        cursor = self.collection.find()
        return await cursor.to_list(length=1000)
    
    async def list_news_filtered(self, filters: dict):
        cursor = self.collection.find(filters).sort("published_datetime_utc", -1)
        return await cursor.to_list(length=1000)

    async def save_one_news(self, response: SearchResponse):
        await self.collection.insert_one(response.dict())