from typing import Optional, Union
from urllib.parse import urljoin

from ...types._api_version import ApiVersion
from .._request_handler import AsyncRequestHandler, RequestHandler


class BaseGuardrail:
    def __init__(self, request_handler: Union[RequestHandler, AsyncRequestHandler]):
        self._request_handler = request_handler

    def _pre_get_applicable_guardrails(
        self,
        project_id: str,
        agent_id: Optional[str] = None,
        correlation_id: Optional[str] = None,
        api_version: str = ApiVersion.V1.value,
    ):
        """
        Prepare request data for retrieving applicable guardrails.

        This internal method constructs the URL and payload for getting guardrails
        applicable to a specific project and optionally a specific agent.

        Args:
            project_id: The project identifier (required)
            agent_id: Optional agent/pipeline identifier. When provided, returns
                guardrails applicable to this specific agent. When omitted, returns
                guardrails applicable at the project level.
            correlation_id: Optional correlation ID for tracing
            api_version: API version to use for the request

        Returns:
            RequestData: Prepared request data for the get applicable guardrails endpoint

        Raises:
            ValueError: If an invalid API version is provided
        """
        if api_version not in ApiVersion.as_list():
            raise ValueError(
                f"Invalid API version: {api_version}. Valid versions are: {', '.join(ApiVersion.as_list())}"
            )
        url = urljoin(
            self._request_handler.base_url, f"{api_version}/Guardrail/applicable"
        )

        payload = {
            "projectId": project_id,
            "agentId": agent_id,
        }

        request_data = self._request_handler.prepare_request(
            url=url, payload=payload, correlation_id=correlation_id
        )

        return request_data
