import { app } from 'electron'
import { promises as fs } from 'fs'
import { join } from 'path'

export interface PublishDefaults {
  /** 快捷方式③默认发布方式 */
  mode: 'multi' | 'single' | 'main'
  /** 单屏发布时使用的屏幕编号 */
  screenIndex: number
  /** 多屏发布时是否同时在编辑器屏幕全屏显示 */
  alsoMain: boolean
  /** 单屏轮播自动切换间隔（秒），0 = 不自动切换 */
  intervalSec: number
}

export interface AppSettings {
  projectName: string
  projectVersion: string
  /** JSON 文件读写密码，空 = 不加密 */
  jsonPassword: string
  /** 快捷键识别阈值（毫秒）：数字/方向键需长按超过该值才触发切屏 */
  keyThreshold: number
  /** 锁定/解锁快捷键识别所使用的按键 */
  keyLockKey: string
  publish: PublishDefaults
  /** 上次打开/另存为工程的文件夹，用于记住上次位置 */
  lastDir: string
}

const DEFAULTS: AppSettings = {
  projectName: '智慧农业大数据可视化控制中心',
  projectVersion: '0.1.0',
  jsonPassword: '',
  keyThreshold: 350,
  keyLockKey: 'F9',
  publish: { mode: 'multi', screenIndex: 1, alsoMain: false, intervalSec: 10 },
  lastDir: ''
}

let cache: AppSettings | null = null

function settingsPath(): string {
  return join(app.getPath('userData'), 'settings.json')
}

export async function loadSettings(): Promise<AppSettings> {
  if (cache) return cache
  try {
    const raw = await fs.readFile(settingsPath(), 'utf8')
    const obj = JSON.parse(raw) as Partial<AppSettings>
    cache = { ...DEFAULTS, ...obj, publish: { ...DEFAULTS.publish, ...(obj.publish || {}) } }
  } catch {
    cache = { ...DEFAULTS, publish: { ...DEFAULTS.publish } }
  }
  return cache!
}

export function getSettings(): AppSettings {
  return cache ?? DEFAULTS
}

export async function saveSettings(patch: Partial<AppSettings>): Promise<AppSettings> {
  const cur = await loadSettings()
  cache = { ...cur, ...patch, publish: { ...cur.publish, ...(patch.publish || {}) } }
  await fs.writeFile(settingsPath(), JSON.stringify(cache, null, 2), 'utf8')
  return cache
}
