#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os

if __name__ == '__main__' :
	if len(sys.argv) != 4:
		print("Use: " + sys.argv[0] + " <crit> <cudf> <output>")
		sys.exit()
	
	crit = sys.argv[1]
	cudf_fn = sys.argv[2]
	out_fn = sys.argv[3]
	
	out_f = open(out_fn, "w")
	
	if crit not in ["paranoid", "trendy"]:
		out_f.write("FAIL\nERROR: Invalid criteria.\n")
		sys.exit()
	
	
	print("p2cudf...")
	opb_fn = "/tmp/cudf-solver-tmp-%i.opb" % os.getpid()
	map_fn = "%s.mapping" % opb_fn
	os.system("/usr/bin/java -Xmx700m -jar p2cudf.jar -obj %s -encoding %s %s" % (crit, cudf_fn, opb_fn))
	print("pb2wcnf...")
	wcnf_fn = "/tmp/cudf-solver-tmp-%i.wcnf" % os.getpid()
	os.system("./pb2wcnf -map %s > %s" % (opb_fn, wcnf_fn))
	print("Solving (msuncore)...")
	sol_fn = "/tmp/cudf-solver-tmp-%i.sol" % os.getpid()
	os.system("./msuncore -bmo -T 290 %s > %s" % (wcnf_fn, sol_fn))
	
	
	map_f = open(map_fn, "r")
	var_pkg = {}
	for line in map_f:
		var, sep, pkg_ver = line.strip().partition("=")
		pkg, sep, ver = pkg_ver.partition(" ")
		if var in var_pkg:
			out_f.write("FAIL\nERROR: Repeated variable.\n")
			sys.exit()
		else:
			var_pkg[var] = (pkg, ver)
	map_f.close()
	
	sol_f = open(sol_fn, "r")
	sol_line = []
	for line in sol_f:
		if line[:2] == "v ":
			sol_line = line[2:].strip().split()
		if line[:2] == "s ":
			if line[:15] == "s UNSATISFIABLE":
				out_f.write("FAIL\nUNSATISFIABLE\n")
				print("Done.")
				sys.exit()
	sol_f.close()
	if len(sol_line) == 0:
		out_f.write("FAIL\nERROR: v line not found.\n")
		sys.exit()
	var_val = [-1] * len(var_pkg.keys()) * 2
	for lit in sol_line:
		l = int(lit)
		if l > 0:
			var_val[abs(l)] = 1
		else:
			var_val[abs(l)] = 0
	
	wcnf_f = open(wcnf_fn, "r")
	var_pb = {}
	inside = False
	for line in wcnf_f:
		if line[:2] == "c ":
			if line[:15] == "c var map begin":
				inside = True
				continue
			if line[:13] == "c var map end":
				break
			if inside:
				var, sep, pb = line[2:].partition("=x")
				var_pb[int(var)] = int(pb.strip())
				continue
	wcnf_f.close()
	
	var = 1
	while var < len(var_val):
		if var in var_pb and var_val[var] == 1:
			s_var = str(var_pb[var])
			#print("%i %s %s" % (var, var_pb[var], var_pkg[s_var]))
			if s_var in var_pkg:
				if var_pkg[s_var][0] != "AbstractVariable:" and var_pkg[s_var][1] != "0":
					out_f.write("package: %s\n" % var_pkg[s_var][0])
					out_f.write("version: %s\n" % var_pkg[s_var][1])
					out_f.write("installed: true\n\n")
			else:
				out_f.write("FAIL\nERROR: Variable mapping not found.")
				sys.exit()
		var += 1
	
	os.system("rm /tmp/cudf-solver-tmp-%s.*" % os.getpid())
	print("Done.")
