from typing import Dict, Any
from .base import BaseClient


class AppsAPI:
    def __init__(self, client: BaseClient):
        self.client = client

    def create_app(self, name: str, origin: str) -> Dict[str, Any]:
        """
        Creates a new app using the provided name.

        :param name: App name
        :param origin: App origin
        :return: Created app data dictionary
        :raises ValueError: If name or workspace_secret is not provided
        """
        if not name:
            raise ValueError("The 'name' is required.")

        headers = {
            "Authorization": self.client.workspace_secret
        }
        path = f"/apps"
        files = {
            "name": (None, name),
            "origin": (None, origin),
            "workspace_id": (None, self.client.workspace_id),
        }  # multipart/form-data

        data = self.client.request("POST", path, headers=headers, files=files)
        return data or {}

    def get_app_by_id(self, app_id: str) -> Dict[str, Any]:
        """
        Retrieves a app by unique ID.

        :param app_id: App ID
        :return: App data dictionary
        """
        headers = {"Authorization": self.client.app_secret}
        path = f"/apps/{app_id}"
        data = self.client.request("GET", path, headers=headers)
        return data or {}

    def list_apps(self) -> Dict[str, Any]:
        """
        Lists apps.

        :return: Dictionary with apps list
        """
        headers = {"Authorization": self.client.workspace_secret}
        path = f"/apps"
        return self.client.request("GET", path, headers=headers) or {}

    def delete_app(self, app_id: str) -> bool:
        """
        Deletes the app by ID.

        :param app_id: ID of the app to delete
        :return: True if deletion was successful
        :raises ValueError: If app_id is missing
        """
        if not app_id:
            raise ValueError("The 'app_id' is required.")

        headers = {
            "Authorization": self.client.workspace_secret,
        }
        path = f"/apps/{app_id}"
        response = self.client.request("DELETE", path, headers=headers)

        return response.get("status") == "ok" or response == {}
