import { t } from "../lang";
import { StorageService } from "./StorageService";

const uploadAudioToRunningHub = async (filePath: string): Promise<string> => {
    const uploadResult = await window.$mapi.runninghub.uploadFile({
        filePath,
        fileType: "audio",
    });

    if (!uploadResult.success || !uploadResult.fileName) {
        throw new Error(uploadResult.error || t("RunningHub音频上传失败"));
    }

    return uploadResult.fileName;
};

const resolveSystemVoiceAudioFileName = async (promptId: string): Promise<string> => {
    const preCacheResult = await window.$mapi.aliyun.cosyvoice.getPreCachedVoicePath(promptId);
    if (!preCacheResult.success || !preCacheResult.path) {
        throw new Error(t("系统音色本地文件不存在，请重新打包或清理音色缓存后重试"));
    }

    return uploadAudioToRunningHub(preCacheResult.path);
};

const resolveCustomVoiceAudioFileName = async (promptId: number | string): Promise<string> => {
    const prompt = await StorageService.get(promptId as any);
    if (!prompt) {
        throw new Error(t("声音音色不存在"));
    }

    if (prompt.content?.runninghubAudioFileName) {
        return prompt.content.runninghubAudioFileName;
    }

    const audioPath = prompt.content?.url || prompt.content?.audioPath;
    if (!audioPath) {
        throw new Error(t("声音音色没有可用于RunningHub的音频文件"));
    }

    const fileName = await uploadAudioToRunningHub(audioPath);
    prompt.content.runninghubAudioFileName = fileName;
    if (prompt.id) {
        await StorageService.update(prompt.id, prompt);
    }

    return fileName;
};

export const resolveRunningHubAudioFileName = async (
    promptId: number | string | undefined,
): Promise<string> => {
    if (!promptId) {
        throw new Error(t("请先选择声音音色"));
    }

    const promptKey = String(promptId);
    if (promptKey.startsWith("sys_")) {
        return resolveSystemVoiceAudioFileName(promptKey);
    }

    return resolveCustomVoiceAudioFileName(promptId);
};
