import time


def wait_for_compute_jobs(nevermined, account, jobs):
    """Monitor and wait for compute jobs to finish.

    Args:
        nevermined (:py:class:`nevermined_sdk_py.Nevermined`): A nevermined instance.
        account (:py:class:`contracts_lib_py.account.Account`): Account that published
            the compute jobs.
            jobs (:obj:`list` of :obj:`tuple`): A list of tuples with each tuple
                containing (service_agreement_id, compute_job_id).

    Returns:
        :obj:`list` of :obj:`str`: Returns a list of dids produced by the jobs

    Raises:
        ValueError: If any of the jobs fail

    """
    failed = False
    dids = set()
    while True:
        finished = 0

        for i, (sa_id, job_id) in enumerate(jobs):
            status = nevermined.assets.compute_status(sa_id, job_id, account)
            print(f"{job_id}: {status['status']}")

            if status["status"] == "Failed":
                failed = True
            if status["status"] == "Succeeded":
                finished += 1
                dids.add(status["did"])

        if failed:
            for i, (sa_id, job_id) in enumerate(jobs):
                logs = nevermined.assets.compute_logs(sa_id, job_id, account)
                for line in logs:
                    print(f"[{line['podName']}]: {line['content']}")
            raise ValueError("Some jobs failed")
        if finished == len(jobs):
            break
        # move up 4 lines
        print("\u001B[4A")
        time.sleep(5)

    return list(dids)