import os 
import re 
import argparse 
from pathlib import Path 

def get_latest_results (base_path_str ):
    """
    指定された結果ディレクトリ内の各タスクについて、
    最新のログファイルから正解率と切り捨て率を抽出して表示します。

    Args:
        base_path_str (str): 結果が格納されているベースディレクトリのパス。
    """

    base_path =Path (base_path_str ).expanduser ()

    if not base_path .is_dir ():
        print (f"Error: Directory not found at '{base_path }'")
        return 

    print (f"Processing directory: {base_path }\n")


    ansi_escape =re .compile (r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')


    task_dirs =sorted ([d for d in base_path .iterdir ()if d .is_dir ()])

    for task_dir in task_dirs :
        task_name =task_dir .name 


        log_files =list (task_dir .glob ('*.log'))

        if not log_files :
            continue 


        latest_log_file =max (log_files ,key =lambda f :f .stat ().st_mtime )

        correct_line ="Correct line not found."
        truncated_line ="Truncated line not found."

        try :
            with open (latest_log_file ,'r',encoding ='utf-8')as f :
                for line in f :

                    clean_line =ansi_escape .sub ('',line ).strip ()
                    if clean_line .startswith ("Correct:"):
                        correct_line =clean_line 
                    elif clean_line .startswith ("Truncated"):
                        truncated_line =clean_line 
        except Exception as e :
            print (f"Error reading file {latest_log_file }: {e }")
            continue 


        print (f"--- Task: {task_name } ---")
        print (f"  Latest Log: {latest_log_file .name }")
        print (f"  {correct_line }")
        print (f"  {truncated_line }")
        print ("-"*(len (task_name )+12 ))
        print ()

if __name__ =='__main__':

    parser =argparse .ArgumentParser (
    description ="Extracts the latest results from log files in task-specific directories."
    )


    parser .add_argument (
    '--path',
    type =str ,

    default ='~/lltm/02_codeexec_etcot/scripts/ET-CoT/output_results/Meta-Llama-3-8B-Instruct/3epoch/LLTM-all-numeric-depth',
    help ='The base path to the results directory. If not provided, a default path will be used.'
    )


    args =parser .parse_args ()


    get_latest_results (args .path )
