import os
import glob
import re

# exact infos from the files
def extract_info(file_path):
    """提取关键信息"""
    area_info = []
    sram_timing = []
    error_msgs = []
    
    with open(file_path, 'r') as f:
        lines = f.readlines()
        in_area = False
        
        for i, line in enumerate(lines):
            # 提取Area信息块
            if line.strip().startswith("1. Area"):
                area_info = lines[i:i+8]
                break  # 每个文件只提取第一个Area块
            
        # 提取时序信息（直接搜索tcyc到tbwh）
        tcyc_line = next((i for i, line in enumerate(lines) if line.strip().startswith("2.2 SRAM timing")), None)
        tbwh_line = next((i for i, line in enumerate(lines) if line.strip().startswith("tbwh")), None)
        if tbwh_line is None:
            tbwh_line = tcyc_line + 10

        if tcyc_line is not None and tbwh_line is not None:
            sram_timing = lines[tcyc_line+2:tbwh_line+1]
        else:
            print(f"Warning: Timing info not found in {file_path}")

        # 新增数值提取逻辑
        tcyc_value = None
        tcd_value = None
        
        # 提取时序值
        for line in lines:
            line_clean = line.strip()
            # 提取tcyc值
            if line_clean.startswith('tcyc'):
                parts = line_clean.split()
                if len(parts) >= 2:
                    val_str = parts[1]
                    print(f"Processing tcyc value: {val_str}")
                    try:
                        tcyc_value = float(val_str)
                        if tcyc_value > 0.8:
                            error_msgs.append(f"Error: tcyc OVER ({tcyc_value}ns > 0.8ns)")
                    except ValueError:
                        pass
            # 提取tcd值
            elif line_clean.startswith('tcd'):
                parts = line_clean.split()
                if len(parts) >= 2:
                    val_str = parts[1]
                    print(f"Processing tcyc value: {val_str}")
                    try:
                        tcd_value = float(val_str)
                        if tcd_value > 0.6:
                            error_msgs.append(f"Error: tcd OVER ({tcd_value}ns > 0.6ns)")
                    except ValueError:
                        pass
        # get the area value
        area_value = 'N/A'
        if len(area_info) >= 4:
            area_line = area_info[3].strip().split()
            if len(area_line) >= 3:
                area_value = area_line[2]

        tcyc_str = f"{tcyc_value:.4f}" if tcyc_value else "N/A"
        tcd_str  = f"{tcd_value:.4f}" if tcd_value else "N/A"
        conclusion = f"[Conclusion]\nArea: {area_value}    tcyc: {tcyc_str}    tcd: {tcd_str}"


    return area_info, sram_timing, error_msgs, conclusion 

# write info into files
def write_info():
    output = []
    
    # 递归所有子目录
    for root, _, files in os.walk('.'):
        # 匹配目标文件模式
        for ds_file in glob.glob(os.path.join(root, '*_ssgnp0p72v125c.ds')):
            print(f"Processing: {ds_file}")
            area, timing, error_msgs, conclusion = extract_info(ds_file)
            
            output.append(f"[DS]======== {os.path.basename(ds_file)} ==========\n")
            output.append("[Area Info]\n")
            output.extend(area)
            output.append("[Timing Info]\n")
            output.extend(timing)
            output.append("\n")
            output.append(conclusion + "\n")
            if error_msgs:
                output.append("\n")
                print (f"Errors found in {ds_file}: {error_msgs}")
                output.extend([msg + "\n" for msg in error_msgs])
            output.append("\n" + "="*80 + "\n")
            # Finally
            output.append("\n")

    # 写入结果文件
    with open('area_and_timing.txt', 'w') as f:
        f.writelines(output)

# parse the area_and_timig.txt file    
def parse_summary():
    spec_dict = {}
    processed_ds = set()  # 新增：用于跟踪已处理的DS文件

    with open('area_and_timing.txt', 'r') as f:
        current_spec = None
        current_ds = None
        for line in f:
            if line.startswith('[DS]'):
                ds_name = line.split('========')[1].strip().split()[0]
                if match := re.search(r'(\d+x\d+)', ds_name):
                    current_spec = match.group(1)
                    current_ds = ds_name
                else:
                    current_spec = None
                    current_ds = None
                    
            elif line.startswith('Area:'):
                if current_spec and current_ds:
                    # 新增去重判断
                    if current_ds not in processed_ds:
                        new_line = f"{line.strip()}   From {current_ds}"
                        spec_dict.setdefault(current_spec, []).append(new_line)
                        processed_ds.add(current_ds)  # 记录已处理文件

    # ... 保持后续写入代码不变 ...

    # 追加汇总信息到文件
    with open('area_and_timing.txt', 'a') as f:
        f.write("\n\n[Summary]")
        for spec, values in spec_dict.items():
            f.write(f"\n== {spec} ==\n")
            f.write('\n'.join(values))

if __name__ == "__main__":
    write_info()
    parse_summary()  # 新增汇总解析       
