import transport
from io import StringIO
import cms
import copy
import json
import os
import smart.cmd

@cms.Plugin(mimetype='application/json',method='GET')
def get (**_args) :
    """
    This function will return the list of labels available
    """
    transport.registry.load()
    _data = copy.copy(transport.registry.DATA)
    _context = _args['config']['system']['context']
    print ()
    
    _CATALOGS = _args['config']['system']['source'].get('catalogs',{})
    _HAS_LLM = 'llm' in _args['config']['system']['source']
    _labels = []
    for _key in _data :
        
        if _key not in  ['default','email','version'] :
            _provider = _data[_key]['provider']
            _name = None
            if 'table' in _data[_key] :
                _name = 'table'
            elif 'collection' in _data[_key] :
                _name = 'collection'
            _table = 'NA' if not _name else _data[_key][_name]
            _plugins = [] if 'plugins' not in _data[_key]else _data[_key]['plugins']
            _icon = f'{_context}/api/disk/read?uri=www/html/_assets/images/{_provider}.png'
            _icon = f'_assets/images/{_provider}.png'
            _labels.append({"label":_key,"provider":_provider,'table':_table,'icon':_icon,'AI': (_provider in _CATALOGS and _HAS_LLM)})
        else:
            continue
    return _labels
def gethostname ():
    return 
@cms.Plugin(mimetype="application/json",method="POST")
def add(**_args):
    """
    adding a label to the registry
    """
    _request = _args['request']
    _entry = _request.json
    _label = _entry['label']
    del _entry['label']
    f  = StringIO(json.dumps(_entry))
    #
    # @TODO: We need to test the parameters and return the response to the client
    #
    #
    # Let us make sure the registry exists
    if not transport.registry.exists() :
        _host = smart.cmd.read(cmd='hostname').replace("\\n'",'').replace("\n","")
        # _host = os.environ['HOSTNAME'] if 'HOSTNAME' in os.environ else os.environ['COMPUTERNAME']
        _email = _host+'@data-transport.co'
        transport.registry.init(_email)

    transport.registry.set(_label,f)

    #
    # now we can/should get the rest of the list
    return get(**_args)

@cms.Plugin(mimetype="application/json",method="GET")
def technologies(**_args):
    return transport.supported().to_html(index=0)