import axios from 'axios'
import * as fs from 'fs'
import * as path from 'path'
import { app } from 'electron'
import { AUTH_SERVER_URL } from './auth/config'
import { withoutUnsupportedProxy } from './httpClient'

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
    update_url: string
}

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

const FALLBACK: 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',
    update_url: ''
}

function getConfigFilePath(): string {
    try {
        return path.join(app.getPath('userData'), 'systemConfig.json')
    } catch {
        return path.join(process.cwd(), 'data', 'systemConfig.json')
    }
}

function loadFromFile(): SystemConfig | null {
    try {
        const filePath = getConfigFilePath()
        if (fs.existsSync(filePath)) {
            const data = fs.readFileSync(filePath, 'utf-8')
            const parsed = JSON.parse(data)
            if (parsed && typeof parsed === 'object') {
                return { ...FALLBACK, ...parsed }
            }
        }
    } catch {}
    return null
}

function saveToFile(config: SystemConfig): void {
    try {
        const filePath = getConfigFilePath()
        const dir = path.dirname(filePath)
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true })
        }
        fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8')
    } catch {}
}

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

    try {
        const baseUrl = AUTH_SERVER_URL.replace(/\/api\/?$/, '').replace(/\/$/, '')
        const response = await axios.get(`${baseUrl}/api/system/config/public`, withoutUnsupportedProxy({
            timeout: 5000,
            params: { _t: now },
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                Pragma: 'no-cache'
            }
        }))
        if (response.data?.success && response.data?.config) {
            cachedConfig = { ...FALLBACK, ...response.data.config }
            lastFetchTime = now
            saveToFile(cachedConfig)
            return cachedConfig
        }
    } catch (error) {
        console.warn('[ElectronSystemConfig] 获取系统配置失败:', error)
    }

    return cachedConfig || loadFromFile() || FALLBACK
}

export function getElectronSystemConfigSync(): SystemConfig {
    if (cachedConfig) return cachedConfig
    const fileConfig = loadFromFile()
    if (fileConfig) {
        cachedConfig = fileConfig
        return cachedConfig
    }
    return FALLBACK
}

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