import { AppConfig } from '../config'

export interface SystemConfig {
    aliyun_bailian_api_key: string
    aliyun_bailian_base_url: string
    aliyun_oss_access_key_id: string
    aliyun_oss_access_key_secret: string
    aliyun_oss_bucket: string
    aliyun_oss_region: string
    volcengine_api_key: string
    volcengine_model: string
    runninghub_api_key: string
    runninghub_workflow_id_1: string
    runninghub_workflow_id_2: string
    runninghub_tts_webapp_id_v2: string
    runninghub_tts_webapp_id_v3: string
    runninghub_tts_v2_audio_node: string
    runninghub_tts_v2_text_node: string
    runninghub_tts_v2_emotion_node: string
    cloud_beauty_base_url: string
    cloud_beauty_api_key: string
    cloud_beauty_default_mode: string
    cloud_beauty_enabled: string
}

const FALLBACK_CONFIG: SystemConfig = {
    aliyun_bailian_api_key: '',
    aliyun_bailian_base_url: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    aliyun_oss_access_key_id: '',
    aliyun_oss_access_key_secret: '',
    aliyun_oss_bucket: '',
    aliyun_oss_region: 'oss-cn-beijing',
    volcengine_api_key: '',
    volcengine_model: 'doubao-seed-2-0-mini-260215',
    runninghub_api_key: '',
    runninghub_workflow_id_1: '2013514129943826433',
    runninghub_workflow_id_2: '2013514129943826433',
    runninghub_tts_webapp_id_v2: '1965614643077070850',
    runninghub_tts_webapp_id_v3: '2028779949334728706',
    runninghub_tts_v2_audio_node: '13',
    runninghub_tts_v2_text_node: '14',
    runninghub_tts_v2_emotion_node: '15',
    cloud_beauty_base_url: '',
    cloud_beauty_api_key: '',
    cloud_beauty_default_mode: '256m',
    cloud_beauty_enabled: 'false'
}

let cachedConfig: SystemConfig | null = null
let lastFetchTime = 0

function getBaseUrl(): string {
    return AppConfig.apiBaseUrl.replace(/\/api\/?$/, '')
}

export async function fetchSystemConfig(): Promise<SystemConfig> {
    const now = Date.now()

    try {
        const baseUrl = getBaseUrl()
        const response = await fetch(`${baseUrl}/api/system/config/public?_t=${now}`, {
            cache: 'no-store'
        })
        const data = await response.json()

        if (data.success && data.config) {
            cachedConfig = { ...FALLBACK_CONFIG, ...data.config }
            lastFetchTime = now
            return cachedConfig
        }
    } catch (error) {
        console.warn('[SystemConfig] 获取系统配置失败，使用兜底配置:', error)
    }

    return cachedConfig || FALLBACK_CONFIG
}

export function getSystemConfigSync(): SystemConfig {
    return cachedConfig || FALLBACK_CONFIG
}

export function clearConfigCache(): void {
    cachedConfig = null
    lastFetchTime = 0
}

export async function getAliyunBailianApiKey(): Promise<string> {
    const config = await fetchSystemConfig()
    return config.aliyun_bailian_api_key
}

export async function getAliyunOssConfig(): Promise<{
    accessKeyId: string
    accessKeySecret: string
    bucket: string
    region: string
}> {
    const config = await fetchSystemConfig()
    return {
        accessKeyId: config.aliyun_oss_access_key_id,
        accessKeySecret: config.aliyun_oss_access_key_secret,
        bucket: config.aliyun_oss_bucket,
        region: config.aliyun_oss_region
    }
}

export async function getVolcengineConfig(): Promise<{
    apiKey: string
    model: string
}> {
    const config = await fetchSystemConfig()
    return {
        apiKey: config.volcengine_api_key,
        model: config.volcengine_model
    }
}

export async function getRunningHubApiKey(): Promise<string> {
    const config = await fetchSystemConfig()
    return config.runninghub_api_key
}
