# --- NSGA-III + CAESES ---

import os, json, time, numpy as np

from pymoo.core.problem import ElementwiseProblem
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.optimize import minimize
from pymoo.util.ref_dirs import get_reference_directions

# ========= Load setup =========
with open("setup.json") as f:
    setup = json.load(f)

specs = setup["designVariables"]

n_var = len(specs)
n_obj = int(setup.get("nObjectives", 1))
n_constr = int(setup.get("nConstraints", setup.get("nIenqualityConstraints", 0)))

xl = np.array([d["lower_bound"] for d in specs], float)
xu = np.array([d["upper_bound"] for d in specs], float)


# ========= Problem =========
class CAESESProblem(ElementwiseProblem):
    def __init__(self):
        super().__init__(
            n_var=n_var,
            n_obj=n_obj,
            n_constr=n_constr,
            xl=xl,
            xu=xu
        )
        self._feval = -1

    def _evaluate(self, x, out, *args, **kwargs):

        # Copy design vector
        x_eval = np.array(x, dtype=float)

        # First three design variables are integers
        x_eval[:3] = np.round(x_eval[:3])

        # 1. Send design variables to CAESES
        with open("in.json", "w") as f:
            json.dump(
                {"designs": [{"dv": x_eval.tolist()}]},
                f,
                indent=2
            )

        with open("in.ready", "w") as f:
            f.write("1")

        # 2. Wait for CAESES result
        while not os.path.exists("out.ready"):
            time.sleep(0.05)

        # 3. Read CAESES output
        with open("out.json") as f:
            resj = json.load(f)

        design = resj["designs"][0]

        F = np.array(design["objectives"], float)

        if n_constr > 0:
            G = -np.array(design["constraints"], float)
            out["G"] = G
        else:
            out["G"] = np.zeros(0)

        out["F"] = F[:n_obj]

        self._feval += 1

        # Store the sequential evaluation ID in the pymoo individual
        out["eval_id"] = self._feval

        print(
            f"Evaluation {self._feval}: "
            f"X = {x_eval.tolist()}, "
            f"F = {out['F'].tolist()}"
        )

        print(f"Evaluation {self._feval}: X = {x_eval}, F = {out['F']}")

        # 4. Cleanup files
        for fp in ("out.json", "out.ready", "in.json", "in.ready"):
            if os.path.exists(fp):
                os.remove(fp)


# ========= Run NSGA-III =========
problem = CAESESProblem()

ref_dirs = get_reference_directions(
    "das-dennis",
    n_dim=n_obj,
    n_partitions=4
)

algorithm = NSGA3(
    pop_size=len(ref_dirs),
    ref_dirs=ref_dirs
)

res = minimize(
    problem,
    algorithm,
    seed=1,
    termination=("n_gen", 10),
    save_history=True,
    verbose=True
)

# ========= Save results =========
# Make a copy so res.X is not modified
X_out = np.array(res.X, copy=True)

# Convert the first three design variables to integers
X_out[:, :3] = np.round(X_out[:, :3]).astype(int)

# Flip the sign of the last objective
F_out = np.array(res.F, copy=True)
F_out[:, -1] *= -1

with open("results.txt", "w") as f:
    f.write("Optimization Finished\n")
    f.write("=====================\n\n")

    f.write("Final Pareto Front\n")
    f.write("------------------\n\n")

    f.write("Design IDs:\n")
    f.write(str(res.opt.get("eval_id")))

    f.write("\n\nDesign Variables (X):\n")
    f.write(str(X_out))

    f.write("\n\nObjective Values (F):\n")
    f.write(str(F_out))
