const { contextBridge, ipcRenderer } = require('electron');
const fs = require('fs');
const path = require('path');
const os = require('os');

const userDataPath = path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと');
const settingsPath = path.join(userDataPath, 'settings.json');
const boundsPath = path.join(userDataPath, 'child_window.json');

// フォルダの存在を保証
function ensureDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
}

// JSONファイルを安全に読み込む
function readJsonSafe(filePath) {
  try {
    return JSON.parse(fs.readFileSync(filePath, 'utf8'));
  } catch {
    return null;
  }
}

// JSONファイルを安全に保存
function writeJsonSafe(filePath, data) {
  try {
    ensureDir(path.dirname(filePath));
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
  } catch (e) {
    console.error(`[writeJsonSafe] 書き込み失敗: ${filePath}`, e);
  }
}

contextBridge.exposeInMainWorld('electronAPI', {
  // ✅ ウィンドウ制御
  minimize: () => ipcRenderer.send('window-minimize'),
  maximize: () => ipcRenderer.send('window-maximize'),
  close: () => ipcRenderer.send('window-close'),

  // ✅ 子ウィンドウ起動
  openChildWindow: (data) => ipcRenderer.send('open-child-window', data),

  // ✅ 子ウィンドウデータ受け取り
  onSetUrl: (callback) => ipcRenderer.on('set-url', (event, data) => callback(data)),

  // ✅ 各種パス取得
  getMessageUrl: () => 'http://busyuka.mydns.jp:6500/FFXI/launcher/message.json',
  getUserDataPath: () => userDataPath,

  // ✅ 設定ファイルの操作
  getSettings: () => {
    const saved = readJsonSafe(settingsPath) || {};
    return {
      voice: typeof saved.voice === 'boolean' ? saved.voice : true,
      backgroundAlt: typeof saved.backgroundAlt === 'boolean' ? saved.backgroundAlt : false
    };
  },
  saveSettings: (settings) => {
    const current = readJsonSafe(settingsPath) || {};
    const updated = Object.assign({}, current, settings);
    writeJsonSafe(settingsPath, updated);
  },

  // ✅ 任意ファイル保存／読み込み
  saveFile: (filePath, content) => {
    try {
      ensureDir(path.dirname(filePath));
      fs.writeFileSync(filePath, content, 'utf8');
    } catch (e) {
      console.error('[saveFile] ファイル保存エラー:', e);
    }
  },
  readJsonFile: readJsonSafe,

  // ✅ 音声処理（ボタン／挨拶／終了）
  playButtonVoice: (filename) => {
    const setting = readJsonSafe(settingsPath);
    if (setting?.voice === false) return;
    ipcRenderer.send('play-button-voice', filename);
  },
  playGreeting: (zone) => ipcRenderer.send('play-greeting', zone),
  sayByeByeMofu: () => ipcRenderer.send('say-bye'),
  onSayBye: (callback) => ipcRenderer.on('say-bye', () => callback()),

  // ✅ 子ウィンドウ位置・サイズの保存／読み込み
  saveChildWindowBounds: (bounds) => writeJsonSafe(boundsPath, bounds),
  loadChildWindowBounds: () => readJsonSafe(boundsPath)
  // ✅ 音声イベント受信（playGreeting）
  onPlayGreeting: (callback) => ipcRenderer.on('play-greeting', callback)
});
