import os
import time
from pathlib import Path

import numpy as np
import subprocess

class DummyObjective(object):
    name = "dummy"

    @staticmethod
    def compute(graph_state, **kwargs):
        return 1.


class MLU(object):
    name = "mlu"

    WS_TO_RC_BIN = "ws-to-rc"
    RC_EVAL_BIN = "rc-eval"

    REPETITA_BIN = "./repetita"

    @staticmethod
    def compute(graph_state, **kwargs):
        top_file = kwargs['top_file']
        dm_file = kwargs['dm_file']

        use_ecmp = kwargs['use_ecmp']
        wopt_name = kwargs['wopt_name']

        # first: call ws_to_rc tool.

        rc_file = Path(str(top_file).replace(".graph", ".rc"))
        if not rc_file.exists():
            command = [MLU.WS_TO_RC_BIN, "--top_file", top_file,
                                         "--dm_file", dm_file,
                                         "--wopt_name", wopt_name]
            if use_ecmp:
                command.append("--use_ecmp")

            print(f"WS_TO_RC command is {' '.join([str(c) for c in command])}")
            subprocess.run(command, capture_output=False)

        mlu_file = Path(str(rc_file).replace(".rc", ".mlu"))
        if not mlu_file.exists():
            command = [MLU.RC_EVAL_BIN,
                       "--rc_file", rc_file,
                       "--top_file", top_file,
                       "--dm_file", dm_file]
            subprocess.run(command, capture_output=False)
        try:
            with open(mlu_file, "r") as fh:
                mlu = float(fh.readlines()[0].strip())
        except FileNotFoundError:
            print(f"was running command {' '.join([str(c) for c in command])}")
            raise ObjectiveEvaluationException(f"Failed when evaluating routing configuration; the following file is missing: {mlu_file.absolute()}")
        return mlu


class ObjectiveEvaluationException(Exception):
    pass



