const { app, BrowserWindow, shell, dialog } = require('electron');
const fs = require('fs');
const path = require('path');

const DEFAULT_CONFIG = {
  startUrl: 'https://learn.fizzabc.com',
  window: {
    width: 1280,
    height: 800
  }
};
const MIGRATION_VERSION = '2026-05-config-reset-v1';

function isValidHttpUrl(value) {
  try {
    const url = new URL(value);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch (error) {
    return false;
  }
}

function getConfigPaths() {
  const userDataConfigPath = path.join(app.getPath('userData'), 'config.json');
  if (!app.isPackaged) {
    return {
      readPath: path.join(__dirname, 'config.json'),
      writePath: path.join(__dirname, 'config.json'),
      userDataConfigPath
    };
  }

  const packagedConfigPath = path.join(process.resourcesPath, 'app', 'config.json');
  const sideBySideConfigPath = path.join(path.dirname(process.execPath), 'config.json');
  if (fs.existsSync(sideBySideConfigPath)) {
    return {
      readPath: sideBySideConfigPath,
      writePath: sideBySideConfigPath,
      userDataConfigPath
    };
  }

  if (fs.existsSync(packagedConfigPath)) {
    return {
      readPath: packagedConfigPath,
      writePath: userDataConfigPath,
      userDataConfigPath
    };
  }

  return {
    readPath: userDataConfigPath,
    writePath: userDataConfigPath,
    userDataConfigPath
  };
}

function getMigrationPaths() {
  const userDataDir = app.getPath('userData');
  return {
    userDataConfigPath: path.join(userDataDir, 'config.json'),
    migrationMarkerPath: path.join(userDataDir, '.migration-version')
  };
}

function runFirstLaunchConfigMigration() {
  if (!app.isPackaged) {
    return;
  }

  const paths = getMigrationPaths();
  try {
    if (fs.existsSync(paths.migrationMarkerPath)) {
      const currentVersion = fs.readFileSync(paths.migrationMarkerPath, 'utf-8').trim();
      if (currentVersion === MIGRATION_VERSION) {
        return;
      }
    }

    // First launch after shipping this migration:
    // remove stale userData config to prevent old URL from overriding packaged config.
    if (fs.existsSync(paths.userDataConfigPath)) {
      fs.unlinkSync(paths.userDataConfigPath);
    }

    fs.mkdirSync(path.dirname(paths.migrationMarkerPath), { recursive: true });
    fs.writeFileSync(paths.migrationMarkerPath, MIGRATION_VERSION, 'utf-8');
  } catch (error) {
    dialog.showErrorBox(
      '配置迁移失败',
      `首次启动配置迁移失败，请检查权限后重试。\n\n错误信息: ${error.message}`
    );
  }
}

function loadConfig() {
  const configPaths = getConfigPaths();
  try {
    if (!fs.existsSync(configPaths.readPath)) {
      fs.mkdirSync(path.dirname(configPaths.writePath), { recursive: true });
      fs.writeFileSync(configPaths.writePath, JSON.stringify(DEFAULT_CONFIG, null, 2), 'utf-8');
      return { ...DEFAULT_CONFIG };
    }

    const raw = fs.readFileSync(configPaths.readPath, 'utf-8');
    const parsed = JSON.parse(raw);
    const merged = {
      ...DEFAULT_CONFIG,
      ...parsed,
      window: {
        ...DEFAULT_CONFIG.window,
        ...(parsed.window || {})
      }
    };

    if (!isValidHttpUrl(merged.startUrl)) {
      dialog.showErrorBox(
        '配置地址无效',
        `config.json 中的 startUrl 无效，已回退默认地址。\n\n当前值: ${String(merged.startUrl)}`
      );
      merged.startUrl = DEFAULT_CONFIG.startUrl;
    }
    return merged;
  } catch (error) {
    dialog.showErrorBox(
      '配置加载失败',
      `读取 config.json 失败，已回退默认配置。\n\n错误信息: ${error.message}`
    );
    return DEFAULT_CONFIG;
  }
}

function createMainWindow(config) {
  const win = new BrowserWindow({
    width: config.window.width,
    height: config.window.height,
    autoHideMenuBar: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true
    }
  });

  win.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url);
    return { action: 'deny' };
  });

  win.webContents.on('will-navigate', (event, url) => {
    try {
      const currentUrl = new URL(win.webContents.getURL() || config.startUrl);
      const targetUrl = new URL(url);
      if (currentUrl.origin !== targetUrl.origin) {
        event.preventDefault();
        shell.openExternal(url);
      }
    } catch (error) {
      event.preventDefault();
      shell.openExternal(url);
    }
  });

  win.loadURL(config.startUrl);
}

app.whenReady().then(() => {
  runFirstLaunchConfigMigration();
  const config = loadConfig();
  createMainWindow(config);

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createMainWindow(config);
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
