import re
import subprocess
import os
import os.path as path
import sys

work_path = sys.path[0]

ffmpeg_path = "ffmpeg"
ffprobe_path = "ffprobe"

record_dir = "record"
record_path = path.join(work_path, record_dir)

if not path.exists(record_path):
    os.mkdir(record_path)

merge_file = path.join(work_path,  "test.mp4")
cmd = f"{ffmpeg_path} -y -loglevel error -f concat -safe 0 -i %s -c copy {merge_file}"


def natural_sort_key(s):
    """
    按文件名中的自然数排序
    """
    # 将字符串按照数字和非数字部分分割，返回分割后的子串列表
    sub_strings = re.split(r'(\d+)', s)
    # 如果当前子串由数字组成，则将它转换为整数；否则将其替换成空字符串
    sub_strings = [int(c) if c.isdigit() else '' for c in sub_strings]
    # 返回子串列表
    return sub_strings

file_list = []
for item in os.listdir(record_path):
    p = path.join(record_path, item)
    if not path.isfile(p) or (not p.endswith(".mp4") and not p.endswith(".rec")):
        continue
    else:
        file_list.append(p)

sorted_file_list = sorted(file_list, key=natural_sort_key)

tmp_merge_file = path.join(work_path, "merge.tmp")
with open(tmp_merge_file, mode="w", encoding="utf8") as f:
    for record in sorted_file_list:
        f.write(f"file '{record}'\n")

proc = subprocess.Popen(
    cmd % tmp_merge_file,
    stdin=None,
    stdout=None,
    shell=True
)

proc.communicate()
os.remove(tmp_merge_file)

meta_cmd = f"{ffprobe_path} -v error -i {merge_file} -print_format json -show_format -show_streams -pretty > {merge_file}.meta.json"

proc = subprocess.Popen(
    meta_cmd,
    stdin=None,
    stdout=None,
    shell=True
)
proc.communicate()