import requests

from openkosmos_ai.nodes.api import ApiConfig, ApiNode
from pydantic import BaseModel


class DifyConsoleAuthConfig(BaseModel):
    api_prefix: str = "/v1"
    email: str
    password: str


class DifyClientConfig(ApiConfig):
    console_auth: DifyConsoleAuthConfig


class DifyClientNode(ApiNode[DifyClientConfig]):
    def __init__(self, config: DifyClientConfig):
        super().__init__(config)
        api_key = DifyClientNode.login(config.base_url, config.console_auth)
        self.config().api_key = api_key

    @staticmethod
    def login(base_url: str, console_auth: DifyConsoleAuthConfig):
        return requests.post(base_url + "/console/api/login", form_data={
            "email": console_auth.email,
            "password": console_auth.password,
            "language": "zh-Hans",
            "remember_me": "true"
        }).json()["data"]["access_token"]

    def console_api_apps(self, page=1, limit=100):
        return self.get("/console/api/apps",
                        params={
                            "page": page,
                            "limit": limit
                        })

    def console_api_apps_export(self, app_id: str):
        return self.get(f"/console/api/apps/{app_id}/export",
                        params={
                            "include_secret": "true",
                        })
