import time
import os
import json

import MathGym.utils.utils as utils
import MathGym.utils.complify as complify
import MathGym.utils.solve as solve

def complify(data, index, client, logger, args):
    """ mutate 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"]
        try:
            formal_problem = complify.mutate(origin_problem, tactic=args.mutation_type, rm_aux=args.remove_aux, \
                                                    allow_real=args.allow_real, simplify=args.simplify, rename=args.rename)
            # if ok == True, then solution is the result; else, the solution is error message
            ok, solution = solve.solve(formal_problem)
        except Exception as e:
            logger.error(origin_problem)
            logger.error(e)
            raise e
        logger.info(f"mutate {file_name}: \n{origin_problem}\n========>>>\n{formal_problem.strip()}\nThe solution from {origin_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