from typing import Tuple, Optional
from pydantic import BaseModel, Field, model_validator

from codemie_tools.base.models import CodeMieToolConfig, CredentialTypes


class ElasticConfig(CodeMieToolConfig):
    credential_type: CredentialTypes = Field(default=CredentialTypes.ELASTIC, exclude=True, frozen=True)
    url: str
    api_key: Optional[Tuple[str, str]] = None

    @model_validator(mode="before")
    def build_api_key_tuple(cls, values):
        """Build api_key tuple from separate api_key_id and api_key fields.

        Supports both naming conventions:
        - api_key_id/api_key (standard)
        - elastic_api_key_id/elastic_api_key (database)
        """
        if isinstance(values.get("api_key"), tuple):
            return values

        api_key_id = values.get("elastic_api_key_id")
        api_key_value = values.get("elastic_api_key")

        if api_key_id and api_key_value and isinstance(api_key_value, str):
            values["api_key"] = (api_key_id, api_key_value)
            values.pop("elastic_api_key_id", None)
            values.pop("elastic_api_key", None)
        elif api_key_id and not api_key_value:
            raise ValueError("Both api_key_id and api_key must be provided together")

        return values


class SearchElasticIndexInput(BaseModel):
    query: str = Field(
        description="""
            String text. It's a query to Elastic API in a form of a Query DSL generated by LLM which
            will be used to find necessary information in a specified index to fulfill user request.
            Important: string formatting and escaping SHOULD NOT be used when passing query to the tool.
            """.strip(),
    )
    index: str = Field(
        description="""
                String text. It's name of the Elastic index which should be used to apply generated query to
                fulfill user request.
                """.strip(),
    )


