"""SQLite tool class for database operations"""

import sqlite3
from typing import Any, List, Optional, Tuple


class SQLiteTool:
    """SQLite tool class for database operations"""
    
    def __init__(self, db_path: str):
        """Initialize SQLite tool
        
        Args:
            db_path: Path to SQLite database file
        """
        self.db_path = db_path
        self._connection: Optional[sqlite3.Connection] = None
        self._cursor: Optional[sqlite3.Cursor] = None
    
    def get_instance(self) -> sqlite3.Connection:
        """Get SQLite database instance
        
        Returns:
            SQLite connection instance
        """
        if self._connection is None:
            self._connection = sqlite3.connect(self.db_path)
            self._cursor = self._connection.cursor()
        return self._connection
    
    def execute(self, sql: str, params: Optional[Tuple[Any, ...]] = None) -> List[Tuple[Any, ...]]:
        """Execute SQL statement
        
        Args:
            sql: SQL statement string
            params: Optional parameters for the SQL statement
            
        Returns:
            List of tuples containing the execution results
        """
        conn = self.get_instance()
        cursor = conn.cursor()
        
        if params:
            cursor.execute(sql, params)
        else:
            cursor.execute(sql)
        
        # For SELECT statements, return the results
        if sql.strip().upper().startswith('SELECT'):
            results = cursor.fetchall()
        else:
            # For other statements, commit and return empty list
            conn.commit()
            results = []
        
        return results
    
    @staticmethod
    def connect_and_execute(db_path: str, sql: str, params: Optional[Tuple[Any, ...]] = None) -> List[Tuple[Any, ...]]:
        """Connect to database, execute SQL statement, and close connection
        
        Args:
            db_path: Path to SQLite database file
            sql: SQL statement string
            params: Optional parameters for the SQL statement
            
        Returns:
            List of tuples containing the execution results
        """
        conn = None
        cursor = None
        results = []
        
        try:
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            if params:
                cursor.execute(sql, params)
            else:
                cursor.execute(sql)
            
            # For SELECT statements, return the results
            if sql.strip().upper().startswith('SELECT'):
                results = cursor.fetchall()
            else:
                # For other statements, commit
                conn.commit()
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()
        
        return results
    
    def close(self):
        """Close database connection"""
        if self._cursor:
            self._cursor.close()
            self._cursor = None
        if self._connection:
            self._connection.close()
            self._connection = None
    
    def __enter__(self):
        """Enter context manager"""
        self.get_instance()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """Exit context manager"""
        self.close()
