import os
import re
# import pandas as pd
import csv
from collections import defaultdict
import argparse

def stats_ship_labels(input_dir, output_file, person="", work_time=""):
    header = [
        "标签", "负责人", "作业时间",
        "军用飞机", "民用飞机", "军民一体飞机",
        "军用轮船", "民用轮船",
        "民用机场", "军用机场", "军民一体机场",
        "民用港口", "军用港口", "军民一体港口",
        "总计"
    ]
    alias = [
        "SAR影像名", "StudentID", "work_time",
        "military_airplane", "civil_airplane", "mix_airplane",
        "military_ship", "civil_ship",
        "civil_airport", "military_airport", "mix_airport",
        "military_harbor", "civil_harbor", "mix_harbor",
        "Total"
    ]

    stats = defaultdict(int)

    for fname in os.listdir(input_dir):
        if not fname.endswith(".txt"):
            continue

        original_name = re.sub(r'_\d+_image\.txt', '', fname)
        file_path = os.path.join(input_dir, fname)

        # with open(file_path, "r", encoding="utf-8") as f:    # 统计的是
        #     for line in f:
        #         parts = line.strip().split()
        #         if len(parts) < 9:
        #             continue
        #         cls = parts[-1]
        #         if cls == "ship":
        #             stats[original_name]["民用轮船"] += 1

        stats[original_name] += 1    # 统计的是有ship的切片数量

    # rows = []
    # for original_name, counts in stats.items():
    #     row = {
    #         "标签":original_name,
    #         "负责人":person,
    #         "作业时间":work_time,
    #         "民用飞机":0,
    #         "军用飞机":0,
    #         "军民一体飞机":0,
    #         "军用轮船":0,
    #         "民用轮船":counts["民用轮船"],
    #         "民用机场":0,
    #         "军用机场":0,
    #         "军民一体机场":0,
    #         "军用港口":0,
    #         "民用港口":0,
    #         "军民一体港口":0
    #     }
    #     row["总计"] = row["民用轮船"]
    #     rows.append(row)
    #
    # df = pd.DataFrame(rows)
    #
    # alias_df = pd.DataFrame([dict(zip(header, alias))])
    # df = pd.concat([alias_df, df], ignore_index=True)
    #
    # total_row = {col:0 for col in header}
    # total_row["标签"] = ""
    # total_row["负责人"] = ""
    # total_row["作业时间"] = ""
    # for col in header[3:]:
    #     total_row[col] = df[col][1:].astype(int).sum()
    # df.loc[len(df)] = total_row
    #
    # df.to_csv(output_file, index=False)
    # print(f"统计完成，结果保存到 {output_file}")

    with open(output_file,"w", newline="",encoding="utf-8") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerow(header)
        writer.writerow(alias)

        total_counts = [0] * (len(header) - 3)

        for original_name, ship_count in stats.items():
            row = [original_name, person, work_time] + [0,0,0,0,ship_count,0,0,0,0,0,0]
            total = ship_count
            row.append(total)

            for i, val in enumerate(row[3:], start=0):
                total_counts[i] += val

            writer.writerow(row)
        total_row = ["","",""] + total_counts
        writer.writerow(total_row)
    print(f"统计完成，结果保存到{output_file}")


def getParams():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i','--inlabelfolder',type=str,default=r'R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\剔除空标注\G6',
                        help='输入tiff的bin文件')
    parser.add_argument('-o', '--outcsvpath',type=str,default=r'D:\TYSAR-德清院\切片工作统计表_0818G6.csv',
                        help='切片文件夹地址')
    parser.add_argument('-p', '--person', type=str, default=f"",
                        help='切片文件夹地址')
    parser.add_argument('-w', '--work_time', type=str, default=f"",
                        help='切片文件夹地址')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = getParams()
    inlabelfolder = args.inlabelfolder
    outcsvpath = args.outcsvpath
    person = args.person
    work_time = args.work_time
    print('inlabelfolder:', inlabelfolder)
    print('outcsvpath:', outcsvpath)
    stats_ship_labels(inlabelfolder,outcsvpath, person, work_time)