import os
import subprocess
import sys

def check_ffmpeg_installed():
    try:
        subprocess.run(
            ["ffmpeg", "-version"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=True
        )
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False

def convert_m4s_to_flac(folder_path):
    if not os.path.isdir(folder_path):
        print(f"错误：文件夹 '{folder_path}' 不存在！")
        return

    m4s_files = [f for f in os.listdir(folder_path) if f.lower().endswith('.m4s')]
    
    if not m4s_files:
        print("未找到任何.m4s格式文件！")
        return

    print(f"共找到 {len(m4s_files)} 个.m4s文件，开始转换...\n")

    for index, filename in enumerate(m4s_files, 1):
        input_file = os.path.join(folder_path, filename)
        output_file = os.path.join(folder_path, os.path.splitext(filename)[0] + '.flac')

        print(f"正在转换 [{index}/{len(m4s_files)}]: {filename}")
        
        try:
            result = subprocess.run(
                [
                    "ffmpeg",
                    "-y",
                    "-i", input_file,
                    "-vn",
                    "-acodec", "flac",
                    output_file
                ],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                encoding="utf-8"
            )

            if result.returncode == 0:
                print(f"✅ 转换成功：{output_file}")
            else:
                print(f"❌ 转换失败：{filename}")
                print(f"错误信息：{result.stderr[:500]}")

        except Exception as e:
            print(f"❌ 处理文件 {filename} 时发生异常：{str(e)}")
        
        print("-" * 50)

    print("\n✅ 批量转换任务完成！")

if __name__ == "__main__":
    print("=" * 60)
    print("M4S 转 FLAC 批量转换工具 V1.0")
    print(f"开发者：【一块没有梦想的药膏】  ")
    print("说明：本工具基于ffmpeg实现m4s音频批量转flac格式")
    print("=" * 60)
    print()
    
    if not check_ffmpeg_installed():
        print("错误：未检测到ffmpeg，请先安装ffmpeg并确保其在系统PATH中！")
        print("安装参考：")
        print("  - Windows：下载ffmpeg并添加到环境变量")
        print("  - Mac：brew install ffmpeg")
        print("  - Linux：sudo apt install ffmpeg 或 sudo yum install ffmpeg")
        sys.exit(1)

    target_folder = input("请输入包含.m4s文件的文件夹路径：").strip()

    convert_m4s_to_flac(target_folder)
