import re
import ast

class Parser:
    def __call__(self, response):  # 允许 parser(response) 形式
        return self.parse(response)
        
    def parse(self, response):
        if isinstance(response, dict) and 'content' in response:
            response = response['content']

        # 清洗内容（如去除转义）
        original_content = response.replace("\_", "_")
        content = original_content.replace("\\", "")

        try:
            # 匹配所有 {'Action': ...} 形式的字符串
            pattern = r"\{[^{}]*['\"]Action['\"]\s*:\s*[^{}]+\}"
            matches = re.findall(pattern, content)

            actions = []
            for match in matches:
                try:
                    # 使用 ast.literal_eval 安全地解析字符串为 dict
                    parsed = ast.literal_eval(match)
                    if isinstance(parsed, dict) and 'Action' in parsed:
                        actions.append(parsed)
                except Exception:
                    continue  # 忽略无法解析的项

            if actions:
                return {
                    'status': True,
                    'content': actions,
                    'message': f'Found {len(actions)} Action dict(s).',
                    'error_code': ''
                }
            else:
                return {
                    'status': False,
                    'content': [],
                    'message': 'No valid Action dicts found.',
                    'error_code': 'not_found'
                }

        except Exception as err:
            return {
                'status': False,
                'content': [],
                'message': f"Unexpected {type(err)}: {err}.",
                'error_code': 'parse_error'
            }

def extract_answer(text):
    pattern = r"So the final answer is (yes|no)"
    match = re.search(pattern, text, re.IGNORECASE)
    if match:
        return match.group(1)
    return None