#!/usr/bin/env python3
"""Generate tool schema from Python function."""

import inspect
import json
from typing import get_type_hints, get_args, get_origin

def generate_tool_schema(func):
    """Generate OpenAI function schema from Python function."""
    
    sig = inspect.signature(func)
    hints = get_type_hints(func)
    doc = inspect.getdoc(func) or ""
    
    properties = {}
    required = []
    
    for param_name, param in sig.parameters.items():
        if param_name == "self":
            continue
        
        param_type = hints.get(param_name, str)
        param_schema = {"type": python_to_json_type(param_type)}
        
        # Extract description from docstring
        param_schema["description"] = f"Parameter {param_name}"
        
        if param.default == inspect.Parameter.empty:
            required.append(param_name)
        else:
            param_schema["default"] = param.default
        
        properties[param_name] = param_schema
    
    return {
        "type": "function",
        "function": {
            "name": func.__name__,
            "description": doc.split("\n")[0] if doc else func.__name__,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": required
            }
        }
    }

def python_to_json_type(python_type):
    """Convert Python type to JSON schema type."""
    if python_type == str:
        return "string"
    elif python_type == int:
        return "integer"
    elif python_type == float:
        return "number"
    elif python_type == bool:
        return "boolean"
    elif get_origin(python_type) == list:
        return "array"
    elif get_origin(python_type) == dict:
        return "object"
    else:
        return "string"

# Example
def search_database(query: str, limit: int = 10, include_archived: bool = False):
    """Search database for records matching query."""
    pass

schema = generate_tool_schema(search_database)
print(json.dumps(schema, indent=2))
