"""Slim tool: generate_sql — Run local SQL queries with optional file registration."""
import json
from typing import Any, Optional


def generate_sql(
    sql: str,
    register_files: str = "{}",
    max_preview_rows: int = 10,
) -> str:
    """Execute a local SQL query using DuckDB, with optional file registration.

    Args:
        sql: SQL query to execute.
        register_files: JSON string mapping table names to file paths (e.g. '{"sales": "sales.csv"}').
        max_preview_rows: Maximum rows to return in preview (default 10).

    Returns:
        JSON with query results, column info, and row counts.
    """
    from databridge.connectors import query_local

    result: dict[str, Any] = {}

    parsed_files: Optional[dict[str, str]] = None
    if register_files and register_files != "{}":
        parsed_files = json.loads(register_files) if isinstance(register_files, str) else register_files

    result = query_local(sql=sql, register_files=parsed_files, max_preview_rows=max_preview_rows)
    return json.dumps(result, indent=2, default=str)
