import json
import re

def extract_last_code_block(text: str) -> str:
    """
    Extract the last code block from the given text.
    
    Args:
        text (str): The input text containing code blocks
        
    Returns:
        str: The content of the last code block, or None if no code block is found
    """
    code_blocks = re.findall(r'```.*?\n(.*?)```', text, re.DOTALL)
    if not code_blocks:
        code_blocks = re.findall(r'```(.*?)```', text, re.DOTALL)
    return code_blocks[-1].strip() if code_blocks else None

def verify(pred: str, answer: str, meta: dict) -> int:
    """
    Verify if the model's prediction matches the correct answer.
    
    Args:
        pred (str): Model's prediction text
        answer (str): Correct answer
        meta (dict/str): Problem metadata
        
    Returns:
        int: 1 if prediction is correct, 0 otherwise
    """
    if isinstance(answer, str):
        try:
            answer = json.loads(answer)
        except json.JSONDecodeError:
            pass
    
    if isinstance(meta, str):
        meta = json.loads(meta)
    elif not isinstance(meta, dict):
        raise ValueError('meta should be dict or str')
    
    # Extract the final code block
    final_answer = extract_last_code_block(pred)
    if not final_answer:
        return 0
    
    try:
        # Extract and clean the final answer
        final_answer = final_answer.strip()
        gold_answer = answer.strip()
        
        # Clean and compare the answers
        cleaned_final_answer = ' '.join(final_answer.split())
        cleaned_gold_answer = ' '.join(gold_answer.split())
        
        return 1 if cleaned_final_answer == cleaned_gold_answer else 0
    except Exception:
        return 0

if __name__ == '__main__':
    s = verify('```json [{"answer": "test"}]```', 'test', '')
    print(s)