
import sys 
import json 
import re 
import statistics 

def extract_trace (text ):
    """
    与えられたテキストから <trace> と </trace> タグに挟まれた部分を抽出し、
    各行をリストとして返す。タグが見つからない場合は空のリストを返す。
    """
    match =re .search (r"<trace>(.*?)</trace>",text ,re .DOTALL )
    if match :
        return match .group (1 ).strip ().splitlines ()
    else :
        return []

def main ():
    if len (sys .argv )!=2 :
        print ("Usage: {} JSONL_PATH".format (sys .argv [0 ]))
        sys .exit (1 )

    file_path =sys .argv [1 ]
    try :
        with open (file_path ,"r",encoding ="utf-8")as f :
            lines =f .readlines ()
    except Exception as e :
        print ("Failed to read file: {}".format (e ))
        sys .exit (1 )

    trace_line_counts =[]
    for idx ,line in enumerate (lines ,start =1 ):
        try :
            obj =json .loads (line )
        except json .JSONDecodeError as e :
            print ("JSON parsing error on line {}: {}".format (idx ,e ))
            continue 


        content =obj .get ("output",{}).get ("content","")
        trace_lines =extract_trace (content )
        if trace_lines :
            trace_line_counts .append (len (trace_lines ))
        else :
            print ("No <trace> block found on line {}.".format (idx ))

    if not trace_line_counts :
        print ("No valid <trace> blocks found.")
        sys .exit (0 )

    print (len (trace_line_counts ))
    print (max (trace_line_counts ))
    avg =statistics .mean (trace_line_counts )
    med =statistics .median (trace_line_counts )

    print ("Average number of trace lines: {:.2f}".format (avg ))
    print ("Median number of trace lines: {:.2f}".format (med ))

if __name__ =="__main__":
    main ()
