import cvxpy as cp
import numpy as np
import os,sys


def solve_slater_point(Q, alpha, s, Dinv_half, solSavePath = None):
    n = Q.shape[0]
    x = cp.Variable(n)
    obj = cp.Minimize(0.5 * cp.quad_form(x, Q) - alpha * s @ (Dinv_half @ x))
    prob = cp.Problem(obj)
    prob.solve()
    if solSavePath is not None:
        if not os.path.exists(solSavePath):
            np.save(solSavePath, x.value)
        else:
            print("Slater point already exists!\n")
    return x.value, prob.status

def solve_opt(Q, alpha, s, Dinv_half, b, D_half, solSavePath = None):
    n = Q.shape[0]
    x = cp.Variable(n)
    obj = cp.Minimize(cp.norm(D_half@x,1))
    con = [0.5 * cp.quad_form(x, Q) - alpha * s @ (Dinv_half @ x) <= b]
    prob = cp.Problem(obj, con)
    prob.solve()
    if solSavePath is not None:
        if not os.path.exists(solSavePath):
            x.value[np.abs(x.value) < 1e-8] = 0
            np.save(solSavePath, x.value)
        else:
            print("Optimal solution of cvxpy already exists!\n")
    return x.value, prob.status