import json
import os

from utils import parse_answer, logger


def rule_checker_zh(messages, action_list, tools):
    analysis = {
        "format_analysis": "",
        "correct": "yes"
    }
    try:
        tool_message = messages[-2]
        tool_content = tool_message["content"]
        tool_content_obj = parse_answer(tool_content)
        observation_list = tool_content_obj["Observation_List"]

        if len(action_list) != len(observation_list):
            analysis["format_analysis"] += f"Tool生成的Observation_List的数量为{len(observation_list)}，Planner给出的要执行Action_List的数量为{len(action_list)}，两者不相等，生成错误，需要重新生成"
            analysis["correct"] = "no"

    except Exception as e:
        analysis["format_analysis"] += f"Tool生成的格式错误，JSON无法解析，请不要增加//等注释信息，具体错误为：{e}"
        analysis["correct"] = "no"

    rule_checker_result = f"Checker_Tool：\n```json\n{json.dumps(analysis, ensure_ascii=False, indent=4)}\n```"
    logger.info(f"rule_checker\n{rule_checker_result}\n")
    return analysis["correct"], rule_checker_result


def rule_checker_en(messages, action_list, tools):
    analysis = {
        "format_analysis": "",
        "correct": "yes"
    }
    try:
        tool_message = messages[-2]
        tool_content = tool_message["content"]
        tool_content_obj = parse_answer(tool_content)
        observation_list = tool_content_obj["Observation_List"]

        if len(action_list) != len(observation_list):
            analysis["format_analysis"] += f"The number of Observation_List generated by Tool is {len(observation_list)}, and the number of Action_List to be executed given by Planner is {len(action_list)}. The two are not equal, resulting in an error, and need to be regenerated."
            analysis["correct"] = "no"

    except Exception as e:
        analysis["format_analysis"] += f"The format generated by Tool is incorrect, and JSON cannot be parsed. Please do not add comments such as //, etc. The specific error is: {e}"
        analysis["correct"] = "no"

    rule_checker_result = f"Checker_Tool：\n```json\n{json.dumps(analysis, ensure_ascii=False, indent=4)}\n```"
    logger.info(f"rule_checker\n{rule_checker_result}\n")
    return analysis["correct"], rule_checker_result


def checker_tool(messages, action_list, tools, env_info, request_func):
    language = os.getenv("LANGUAGE")
    if language == "zh":
        rule_correct, rule_checker_result = rule_checker_zh(messages, action_list, tools)
    else:
        rule_correct, rule_checker_result = rule_checker_en(messages, action_list, tools)
    return rule_correct, rule_checker_result
