import json
from abc import ABC, abstractmethod
from lib.common import rest_client
from lib.services.rollouts.base_client import BaseClient


class ActionClient(BaseClient):
    """Service client for Rollouts Action API"""

    api_version = "v1"

    def __init__(self, auth_provider, client, **kwargs):
        super().__init__(auth_provider=auth_provider, **kwargs)
        self.client = client

    def _parse_response(self, resp, body, schema):
        """Parse and validate response."""
        if not body or body.strip() == '':
            body_data = {}
        else:
            body_data = json.loads(body)
        self.validate_response(schema, resp, body_data)
        return rest_client.ResponseBody(resp, body_data)

    def trigger_action(self, name, product, trigger):
        """Trigger a rollout action (start, pause, unpause, rollback, promote).

        :param name: Rollout configuration name
        :param product: Product type (apprunner, fke, server)
        :param trigger: Action trigger (start, pause, unpause, rollback, promote)
        """
        url = self.client.get_action_path(
            self.project_name, product, name, trigger
        )
        resp, body = self.post(url, None)
        return self._parse_response(
            resp, body, self.client.get_schema().trigger_action
        )


class ActionClientInterface(ABC):
    """Interface for cloud-specific implementations."""

    @abstractmethod
    def get_schema(self):
        """Return response schemas module."""
        pass

    @abstractmethod
    def get_action_path(self, project, product, name, trigger):
        """Return API endpoint path for triggering a rollout action."""
        pass
