import json
from typing import List, Optional
from datetime import datetime
from .base import TelegramDataProvider, TelegramMessage


class JSONTelegramStorage(TelegramDataProvider):
    """JSON storage implementation for Telegram messages."""
    
    def __init__(self, channel_username: str, proxy_port: Optional[int] = None):
        super().__init__(channel_username, proxy_port)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.filename = f"telegram_{channel_username}_{timestamp}.json"
        self.file_path = self.get_export_path(self.filename)
    
    def store_data(self, messages: List[TelegramMessage]) -> bool:
        """Store messages in JSON file."""
        try:
            data = [msg.to_dict() for msg in messages]
            with open(self.file_path, 'w+', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"Error storing JSON data: {e}")
            return False
    
    def process_data(self, messages: List[TelegramMessage]) -> List[TelegramMessage]:
        """Process messages (filter out empty messages)."""
        return [msg for msg in messages if msg.text.strip()]
