import sqlite3
from typing import List, Dict, Any

class TimelineDB:
    def __init__(self, db_path: str = ":memory:"):
        self.db_path = db_path
        self.conn = sqlite3.connect(db_path, check_same_thread=False)
        self.conn.row_factory = sqlite3.Row
        self._create_tables()

    def _create_tables(self):
        with self.conn:
            self.conn.execute("""
                CREATE TABLE IF NOT EXISTS timeline (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    timestamp REAL NOT NULL,
                    source TEXT NOT NULL,
                    content TEXT NOT NULL
                )
            """)
            self.conn.execute("CREATE INDEX IF NOT EXISTS idx_timestamp ON timeline(timestamp)")
            self.conn.execute("CREATE INDEX IF NOT EXISTS idx_content ON timeline(content)")

    def log_event(self, timestamp: float, source: str, content: str) -> None:
        with self.conn:
            self.conn.execute(
                "INSERT INTO timeline (timestamp, source, content) VALUES (?, ?, ?)",
                (timestamp, source, content)
            )

    def search_timeframe(self, start: float, end: float) -> List[Dict[str, Any]]:
        cursor = self.conn.cursor()
        cursor.execute(
            "SELECT timestamp, source, content FROM timeline WHERE timestamp >= ? AND timestamp <= ? ORDER BY timestamp ASC",
            (start, end)
        )
        return [dict(row) for row in cursor.fetchall()]

    def search_text(self, query: str) -> List[Dict[str, Any]]:
        cursor = self.conn.cursor()
        search_query = f"%{query}%"
        cursor.execute(
            "SELECT timestamp, source, content FROM timeline WHERE content LIKE ? ORDER BY timestamp DESC",
            (search_query,)
        )
        return [dict(row) for row in cursor.fetchall()]

    def close(self):
        self.conn.close()
