"""
This script is written for running Uwe Schöning's WalkSAT algorithm
    [Uwe Schöning:
    A probabilistic algorithm for k-SAT and constraint satisfaction problems.
    In: Proceedings of FOCS 1999, IEEE, pages 410–414.]
via the command line
by specifying the instance to solve, and the seed to use.
Uwe Schöning's WalkSAT algorithm can be seen as a special case of the probSAT algorithm
    [Adrian Balint, Uwe Schöning:
    Choosing Probability Distributions for Stochastic Local Search and the Role of Make versus Break.    
    In: Lecture Notes in Computer Science, 2012, Volume 7317, Theory and Applications of Satisfiability Testing - SAT 2012, pages 16-29.
    https://www.uni-ulm.de/fileadmin/website_uni_ulm/iui.inst.190/Mitarbeiter/balint/SAT2012.pdf]
with exponential function (break-only-exp-algorithm) and c_b = 1.

The script will record the number of flips, the time used, and the seed used.
"""

import argparse
from subprocess import Popen, PIPE
from time import sleep
from os.path import exists
import sys
from timeit import default_timer as timer
import pathlib as pl

def run_alg(instance):
    solve_ext_path = pl.Path("./solve_extended.sh").absolute()

    #p = Popen([solve_ext_path, instance])
    p = Popen(["bash", "./solve_extended.sh", instance], stdin = PIPE, stdout = PIPE, stderr=PIPE)

    output, err = p.communicate()
    rc = p.returncode
    err = err.decode("utf-8") if err else ""
    if err != "":
        print(err, file=sys.stderr)

    return output.decode("utf-8")

def parse_result(res_str):
    res = {}
    
    for line in res_str.splitlines():
        if line.startswith("c restarts"):
            res["restarts"] = int(line.split(":")[1].strip().split(" ")[0])
        elif line.startswith("c conflicts"):
            res["conflicts"] = int(line.split(":")[1].strip().split(" ")[0])
        elif line.startswith("c decisions"):
            res["decisions"] = int(line.split(":")[1].strip().split(" ")[0])
        elif line.startswith("c propagations"):
            res["propagations"] = int(line.split(":")[1].strip().split(" ")[0])
        elif line.startswith("c nb reduced Clauses"):
            res["reduced_clauses"] = int(line.split(":")[1])
        elif line.startswith("c CPU time"):
            res["cpu_time"] = float(line.split(":")[1].strip().split(" ")[0])
        elif line.startswith("s"):
            res["result"] = line.split(" ")[1].strip()

    return res

def parse_instance_path(ipath):
    name = pl.Path(ipath).name.strip()

    ext_nr = int(name[:-len(".cnf.bz2")][-4:])
    instance = name[:-len("_0000.cnf.bz2")]

    return instance, ext_nr 



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--instance", help="The instance.")

    args = parser.parse_args()

    res_str = run_alg(args.instance)


    iname, ext_nr = parse_instance_path(args.instance)
    
    res = parse_result(res_str)
    
    res_vals = [iname, str(ext_nr)] + list(map(str, res.values()))

    print(','.join(res_vals))

    
    

    
