"""SQLite tool for OpenAI Agent"""

from typing import Optional, Tuple, Any, List
from agents import function_tool
from diona.project.tools import SQLiteTool


@function_tool
async def sqlite_tool(
    db_path: str,
    sql: str,
    params: Optional[List[Any]] = None,
    use_instance: bool = False
) -> str:
    """Execute SQLite SQL statements
    
    This tool allows you to perform SQLite database operations such as:
    1. Creating tables
    2. Inserting data
    3. Updating data
    4. Deleting data
    5. Querying data
    
    Important usage guidelines:
    - Always use parameterized queries to prevent SQL injection
    - Specify the correct database path
    - Use appropriate SQL syntax for your operations
    - For SELECT statements, the results will be returned as a list of tuples
    
    Args:
        db_path: Path to the SQLite database file
        sql: SQL statement to execute
        params: Optional list of parameters for the SQL statement
        use_instance: Whether to use instance method (True) or static method (False)
        
    Returns:
        Execution result as a string
    """
    try:
        if params:
            # Convert list to tuple for SQLite
            params_tuple = tuple(params)
        else:
            params_tuple = None
        
        if use_instance:
            # Use instance method
            with SQLiteTool(db_path) as sqlite_tool:
                results = sqlite_tool.execute(sql, params_tuple)
        else:
            # Use static method
            results = SQLiteTool.connect_and_execute(db_path, sql, params_tuple)
        
        # Format the results
        if results:
            # For SELECT statements, return the results
            result_str = "Query results:\n"
            for row in results:
                result_str += f"{row}\n"
        else:
            # For other statements, return success message
            if sql.strip().upper().startswith('SELECT'):
                result_str = "No results found"
            else:
                result_str = "Operation executed successfully"
        
        return result_str
    except Exception as e:
        return f"Error: {str(e)}"
