import json

from openai.types.responses import Response, ResponseFunctionToolCall


def build_search_function() -> dict:
    return {
        "type": "function",
        "name": "search_database",
        "description": "Search PostgreSQL database for relevant products based on user query",
        "parameters": {
            "type": "object",
            "properties": {
                "search_query": {
                    "type": "string",
                    "description": "Query string to use for full text search, e.g. 'red shoes'",
                },
                "price_filter": {
                    "type": "object",
                    "description": "Filter search results based on price of the product",
                    "properties": {
                        "comparison_operator": {
                            "type": "string",
                            "description": "Operator to compare the column value, either '>', '<', '>=', '<=', '='",  # noqa
                        },
                        "value": {
                            "type": "number",
                            "description": "Value to compare against, e.g. 30",
                        },
                    },
                },
                "brand_filter": {
                    "type": "object",
                    "description": "Filter search results based on brand of the product",
                    "properties": {
                        "comparison_operator": {
                            "type": "string",
                            "description": "Operator to compare the column value, either '=' or '!='",
                        },
                        "value": {
                            "type": "string",
                            "description": "Value to compare against, e.g. AirStrider",
                        },
                    },
                },
            },
            "required": ["search_query"],
        },
    }


def extract_search_arguments(original_user_query: str, response: Response):
    search_query = None
    filters = []
    tool_calls = [item for item in response.output if isinstance(item, ResponseFunctionToolCall)]
    if tool_calls:
        for tool_call in tool_calls:
            if tool_call.name == "search_database":
                arg = json.loads(tool_call.arguments)
                search_query = arg.get("search_query", original_user_query)
                if "price_filter" in arg and arg["price_filter"] and isinstance(arg["price_filter"], dict):
                    price_filter = arg["price_filter"]
                    filters.append(
                        {
                            "column": "price",
                            "comparison_operator": price_filter["comparison_operator"],
                            "value": price_filter["value"],
                        }
                    )
                if "brand_filter" in arg and arg["brand_filter"] and isinstance(arg["brand_filter"], dict):
                    brand_filter = arg["brand_filter"]
                    filters.append(
                        {
                            "column": "brand",
                            "comparison_operator": brand_filter["comparison_operator"],
                            "value": brand_filter["value"],
                        }
                    )
    elif response.output_text:
        search_query = response.output_text.strip()
    return search_query, filters
