import sqlite3
from typing import List, Optional
from .base import TelegramDataProvider, TelegramMessage


class SQLiteTelegramStorage(TelegramDataProvider):
    """SQLite storage implementation for Telegram messages."""
    
    def __init__(self, channel_username: str, proxy_port: Optional[int] = None, db_filename: str = "telegram.db"):
        super().__init__(channel_username, proxy_port)
        self.db_filename = db_filename
        self.db_path = self.get_export_path(db_filename)
        self._initialize_db()
    
    def _initialize_db(self):
        """Initialize the SQLite database."""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # Create table with channel name as table name
        table_name = self.channel_username
        cursor.execute(f"""
            CREATE TABLE IF NOT EXISTS {table_name} (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                message_id INTEGER,
                time TEXT NOT NULL,
                text TEXT NOT NULL
            )
        """)
        
        conn.commit()
        conn.close()
    
    def store_data(self, messages: List[TelegramMessage]) -> bool:
        """Store messages in SQLite database."""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            table_name = self.channel_username
            
            # Insert messages
            for msg in messages:
                cursor.execute(f"""
                    INSERT OR IGNORE INTO {table_name} (message_id, time, text)
                    VALUES (?, ?, ?)
                """, (msg.message_id, msg.time.isoformat(), msg.text))
            
            conn.commit()
            conn.close()
            return True
        except Exception:
            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()]
