from typing import Optional
import requests

from smartsupp_client_config import smartsupp_config

class SmartsuppClient:
    def __init__(self, verbose: bool = False):
        self.config = smartsupp_config()
        self.base_url = self.config['smartsupp']['base_url']
        api_key = self.config['smartsupp']['api_key']
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-type': 'application/json'
        }
        
    def visitor(self, visitor_id) -> Optional[str]:
        url = f'{self.base_url}/visitors/{visitor_id}'
        response = requests.get(url, headers=self.headers)

        if response.status_code == 404:
            return None

        response.raise_for_status()
        return response.json()['name']
    
    def conversation(self, conversation_id):
        url = f'{self.base_url}/conversations/{conversation_id}'
        params = {
            'messages': 'true'
        }
        response = requests.get(url, headers=self.headers, params=params)
        response.raise_for_status()
        return response.json()
    
    def send_message(self, conversation_id, message):
        url = f'{self.base_url}/conversations/{conversation_id}/messages'
        agent_id = self.config['smartsupp']['agent_id']
        data = {
            'sub_type': 'agent',
            'agent_id': f'{agent_id}',
            'content': {
                'type': 'text',
                'text': message
            }
        }
        response = requests.post(url, headers=self.headers, json=data)
        response.raise_for_status()
        return response.json()
    
    def typing(self, conversation_id):
        url = f'{self.base_url}/conversations/{conversation_id}/typing'
        data = {
            'active': True
        }
        response = requests.post(url, headers=self.headers, json=data)
        response.raise_for_status()
        return response.json()
        
        
        