import manta_lab as ml
from manta_lab.tuning.internal import FunctionAgent, ProgramAgent

logger = None


class AgentError(Exception):
    pass


def program_agent(api, tune_id, function, entity=None, project=None, count=None):
    ProgramAgent
    return


def function_agent(api, tune_id, function, entity=None, project=None, count=None):
    """Generic agent entrypoint, used for CLI or jupyter.

    Arguments:
        tune_id (dict): Sweep ID generated by CLI or tune API
        function (func, optional): A function to call instead of the "program"
        entity (str, optional): MantaLab Entity
        project (str, optional): MantaLab Project
        count (int, optional): the number of trials to run.
    """
    if not callable(function):
        raise Exception("function paramter must be callable!")
    agent = FunctionAgent(
        api=api,
        tune_id=tune_id,
        function=function,
        entity=entity,
        project=project,
        count=count,
        logger=logger,
    )
    agent.run()


def agent(tune_id, function=None, entity=None, project=None, count=None):
    """
    Generic agent entrypoint.

    Will run a function or program with configuration parameters.
    """
    kwargs = locals()
    global _INSTANCES
    _INSTANCES += 1
    try:
        # make sure we are logged in
        api = ml.api.MantaAPI()
        if function:
            return function_agent(api=api, **kwargs)
        in_jupyter = not ml.util.ensure_python()
        return program_agent(api=api, in_jupyter=in_jupyter, **kwargs)
    finally:
        _INSTANCES -= 1


_INSTANCES = 0


def is_running():
    return bool(_INSTANCES)
