import time
import os
import json

import utils.utils as utils
import utils.simplify as simplify
import utils.solve as solve

def refresh(data, index, client, logger, args):
    """ fresh the problem via fuzzing """
    Q, A = data['question'], data['answer']
    file_name = "problem_%s" %(args.index[0] + index)
    save_file_path = os.path.join(args.save_folder_path, file_name+'.json')
    if not os.path.exists(save_file_path):
        answer = utils.parse_answer(A)
        thy_series = {'problem': Q, 
                    'solution': A, 
                    'answer': answer}
        with open(save_file_path, 'w') as file:  
            json.dump(thy_series, file, indent=4)
    else:
        with open(save_file_path) as file:
            thy_series = json.load(file)
            answer = thy_series['answer']     
    thy = thy_series.get(f'generation_{max(args.save_iter,0)}', {})
    formal_problem, answer = thy.get("formal problem", ""), thy.get("answer", "")
    if (formal_problem != "" and answer != "") and args.overwrite == 0:
        logger.info('skip')
    else:
        t0 = time.time()
        last_thy = thy_series[f"generation_{args.ref_iter}"]
        origin_problem, origin_answer = last_thy["formal problem"], last_thy["answer"]
        formal_problem = simplify.refresh(origin_problem, comment=args.comment)
        ### if ok == True, then solution is the result; else, the solution is error message
        ok, solution = solve.solve(formal_problem)
        logger.info(f"refresh {file_name}: \n{origin_problem}\n========>>>\n{formal_problem}\nThe solution from {last_thy['answer']} to {''.join(solution)}")
        t1 = time.time()
        logger.info('success! In (%s)s' % (t1-t0))
        if ok == False: 
            thy["formal problem"] = origin_problem
            thy["answer"] = origin_answer
        else:
            thy['formal problem'] = formal_problem
            thy['answer'] = ",".join(solution)
        thy["informal problem"] = "" # clean the informal problem
        thy_series.update({f'generation_{max(args.save_iter,0)}' : thy})
        with open(save_file_path, 'w') as file:  
            json.dump(thy_series, file, indent=4)
    return