#!/usr/bin/env python3
"""
使用 AnimeWwise 引擎提取所有 HSR 音频（不依赖 map）。
输出文件以 Wwise ID 命名，后续可交叉引用角色映射。
"""

import os
import sys

AWW_DIR = r"D:\Project\Code\Uni\Cyrene-Voice-Model\tools\AnimeWwise"
sys.path.insert(0, AWW_DIR)
os.chdir(AWW_DIR)

from extract import WwiseExtract

HSR_AUDIO = r"D:\MeowG\Honkai：Star_Rail\StarRail_Data\Persistent\Audio\AudioPackage\Windows\Chinese(PRC)"
OUTPUT_DIR = r"D:\Project\Code\Uni\Cyrene-Voice-Model\data\all_extracted"

print("=" * 60)
print("HSR 全部语音提取 (无 map)")
print("=" * 60)

extractor = WwiseExtract()

# 只提取 VoBanks 文件（角色语音）+ 3.x 剧情
pck_files = sorted([
    os.path.join(HSR_AUDIO, f)
    for f in os.listdir(HSR_AUDIO)
    if f.endswith(".pck") and (
        f.startswith("VoBanks") or
        "External_del_3." in f or
        "External_del_4." in f
    )
])

print(f"\n加载 {len(pck_files)} 个 .pck 文件...")

def progress(data):
    if data[0] == "total" and int(data[1]) % 25 == 0:
        print(f"  {int(data[1])}%")

file_structure = extractor.load_folder(
    _map=None,  # 不用 map
    files=pck_files,
    diff_path="",
    base_path=HSR_AUDIO,
    progress=progress,
)

# 收集所有文件
def collect_all(structure, prefix=""):
    files = []
    for folder_name, folder_content in structure.get("folders", {}).items():
        sub = f"{prefix}/{folder_name}" if prefix else folder_name
        files.extend(collect_all(folder_content, sub))
    for file_entry in structure.get("files", []):
        name, meta = file_entry[0], file_entry[1]
        path_parts = prefix.split("/") if prefix else []
        files.append({
            "path": path_parts,
            "name": name,
            "source": meta["source"],
            "offset": meta["offset"],
            "size": meta["size"],
            "original_name": meta["original_name"],
        })
    return files

all_files = collect_all(file_structure)
print(f"\n找到 {len(all_files)} 个音频文件")

# 提取为 WAV
print(f"\n提取到 {OUTPUT_DIR}...")
os.makedirs(OUTPUT_DIR, exist_ok=True)

extractor.extract_files(
    _input=HSR_AUDIO,
    files=all_files,
    output=OUTPUT_DIR,
    _format="wav",
    progress=progress,
)

print(f"\n完成！文件保存在: {OUTPUT_DIR}")
extractor.reset()
