import aiohttp

class Robot:
    """
    The `Robot` class provides an interface for interacting with the Eitaayar API.

    ### Example Usage:
    ```python
    from eitaapy import Robot
    import asyncio

    async def main():
        api = Robot('YOUR_TOKEN')
        response = await api.get_me()
        print(response)

    asyncio.run(main())
    ```
    """

    def __init__(self, token):
        """
        Initializes the `Robot` instance.

        token: Your API token from Eitaayar.

        ### Example:
        ```python
        api = Robot("YOUR_TOKEN")
        ```
        """
        self.token = token
        self.base_url = f"https://eitaayar.ir/api/{self.token}"

    async def _make_request(self, method_name, params=None, method_type='GET'):
        """
        Internal method to make API requests.

        method_name: API method name.
        params: Parameters to be sent with the request.
        method_type: HTTP method ('GET' or 'POST').
        :return: JSON response from the API.
        """
        url = f"{self.base_url}/{method_name}"
        async with aiohttp.ClientSession() as session:
            if method_type == 'GET':
                async with session.get(url, params=params) as response:
                    return await response.json()
            elif method_type == 'POST':
                headers = {'Content-Type': 'application/json'}
                async with session.post(url, headers=headers, json=params) as response:
                    return await response.json()

    async def get_me(self):
        """
        Retrieves account information from the API.

        :return: Account details in JSON format.

        ### Example:
        ```python
        async def main():
            api = Robot('YOUR_TOKEN')
            response = await api.get_me()
            print(response)

        asyncio.run(main())
        ```
        """
        return await self._make_request('getMe')

    async def send_message(self, chat_id, text, title=None, notification_disable=None, 
                           id_message_to_reply=None, date=None, pin=None, view_count_for_delete=None):
        """
        Sends a message to a chat.

        chat_id : Target chat ID.
        text : Message text.
        title : Message title (optional).
        notification_disable : Disable notifications (optional).
        id_message_to_reply : Message ID to reply to (optional).
        date : Message send date (optional).
        pin : Pin the message (optional).
        view_count_for_delete : Delete message after a specific number of views (optional).
        return: JSON response from the API.

        ### Example:
        ```python
        async def main():
            api = Robot('YOUR_TOKEN')
            response = await api.send_message(chat_id='123456789', text='Hello, World!')
            print(response)

        asyncio.run(main())
        ```
        """
        params = {
            "chat_id": chat_id,
            "text": text,
            "title": title,
            "notification_disable": notification_disable,
            "reply_to_message_id": id_message_to_reply,
            "date": date,
            "pin": pin,
            "viewCountForDelete": view_count_for_delete
        }
        return await self._make_request('sendMessage', params=params, method_type='POST')

    async def send_file(self, chat_id, file, caption=None):
        """
        Sends a file or media to a chat.

        chat_id : Target chat ID.
        file : File path or URL.
        :return: JSON response from the API.

        ### Example:
        ```python
        async def main():
            api = Robot('YOUR_TOKEN')
            response = await api.send_file(chat_id='123456789', file='path/to/file.jpg', caption='This is a file')
            print(response)

        asyncio.run(main())
        ```
        """
        import os,aiofiles
        file_data = None
        file_name = None

        if file.startswith("https://"):
            async with aiohttp.ClientSession() as session:
                async with session.get(file) as resp:
                    if resp.status == 200:
                        file_data = await resp.read()
                        file_name = os.path.basename(file)
                    else:
                        return {"error": f"Failed to download file. Status: {resp.status}"}
        else:
            async with aiofiles.open(file, "rb") as f:
                file_data = await f.read()
                file_name = os.path.basename(file)

        data = aiohttp.FormData()
        data.add_field("chat_id", str(chat_id))
        data.add_field("file", file_data, filename=file_name)
        if caption:
            data.add_field("caption", caption)

        async with aiohttp.ClientSession() as session:
            async with session.post(f"{self.base_url}/sendFile", data=data) as resp:
                return await resp.json()