/**
 * Configuration Management JavaScript
 * Handles loading, editing, and saving configuration for OpenClaw
 */

// Configuration API endpoints
const API_CONFIG = "/api/config";
const API_CONFIG_SCHEMA = "/api/config/schema";

// DOM Elements
const saveBtn = document.getElementById("saveBtn");
const resetBtn = document.getElementById("resetBtn");
const reloadBtn = document.getElementById("reloadBtn");
const statusMessage = document.getElementById("statusMessage");

// Store original config for reset functionality
let originalConfig = null;
let currentConfig = null;

/**
 * Initialize the configuration page
 */
document.addEventListener("DOMContentLoaded", () => {
  loadConfiguration();
  setupEventListeners();
});

/**
 * Setup event listeners for buttons
 */
function setupEventListeners() {
  saveBtn.addEventListener("click", saveConfiguration);
  resetBtn.addEventListener("click", resetConfiguration);
  reloadBtn.addEventListener("click", loadConfiguration);
}

/**
 * Load configuration from the API
 */
async function loadConfiguration() {
  try {
    showStatus("正在加载配置...", "info");

    const response = await fetch(API_CONFIG);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const config = await response.json();

    if (config.error) {
      throw new Error(config.error);
    }

    originalConfig = JSON.parse(JSON.stringify(config)); // Deep copy
    currentConfig = config;

    populateForm(config);
    hideStatus();

    console.log("配置加载成功");
  } catch (error) {
    console.error("加载配置时出错:", error);
    showStatus(`加载配置失败: ${error.message}`, "error");
  }
}

/**
 * Populate form fields with configuration values
 */
function populateForm(config) {
  // Trading settings
  if (config.trading) {
    setInputValue("initialCapital", config.trading.initial_capital);
    setInputValue("maxPositionSize", config.trading.max_position_size);
    setInputValue("stopLoss", config.trading.stop_loss_percent);
  }

  // Agent settings
  if (config.agents) {
    setInputValue("agentCount", config.agents.count);
    setSelectValue("strategy", config.agents.default_strategy);
  }

  // Market data settings
  if (config.market_data) {
    setInputValue("symbols", config.market_data.symbols?.join(","));
    setSelectValue("dataProvider", config.market_data.provider);
  }

  // System settings
  if (config.system) {
    setSelectValue("logLevel", config.system.log_level);
    setInputValue("updateInterval", config.system.update_interval);
  }
}

/**
 * Collect form data into configuration object
 */
function collectFormData() {
  const config = {
    trading: {
      initial_capital: parseFloat(getInputValue("initialCapital")) || 10000,
      max_position_size: parseFloat(getInputValue("maxPositionSize")) || 20,
      stop_loss_percent: parseFloat(getInputValue("stopLoss")) || 5,
    },
    agents: {
      count: parseInt(getInputValue("agentCount")) || 4,
      default_strategy: getSelectValue("strategy") || "hybrid",
    },
    market_data: {
      symbols: getInputValue("symbols")
        ?.split(",")
        .map((s) => s.trim())
        .filter((s) => s) || ["AAPL", "GOOGL"],
      provider: getSelectValue("dataProvider") || "yfinance",
    },
    system: {
      log_level: getSelectValue("logLevel") || "INFO",
      update_interval: parseInt(getInputValue("updateInterval")) || 5,
    },
  };

  return config;
}

/**
 * Save configuration to the API
 */
async function saveConfiguration() {
  try {
    saveBtn.disabled = true;
    saveBtn.textContent = "保存中...";

    const config = collectFormData();

    const response = await fetch(API_CONFIG, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(config),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();

    if (result.status === "error") {
      throw new Error(result.message);
    }

    originalConfig = JSON.parse(JSON.stringify(config));
    currentConfig = config;

    showStatus("配置保存成功！", "success");
    console.log("配置已保存:", result);
  } catch (error) {
    console.error("保存配置时出错:", error);
    showStatus(`保存配置失败: ${error.message}`, "error");
  } finally {
    saveBtn.disabled = false;
    saveBtn.textContent = "保存配置";
  }
}

/**
 * Reset configuration to original values
 */
function resetConfiguration() {
  if (originalConfig) {
    populateForm(originalConfig);
    showStatus("配置已重置为上次保存的值", "info");
    setTimeout(hideStatus, 3000);
  } else {
    showStatus("没有可重置的已保存配置", "error");
  }
}

/**
 * Show status message
 */
function showStatus(message, type) {
  statusMessage.textContent = message;
  statusMessage.className = `status-message ${type}`;
}

/**
 * Hide status message
 */
function hideStatus() {
  statusMessage.className = "status-message";
  statusMessage.textContent = "";
}

/**
 * Helper: Get input value by ID
 */
function getInputValue(id) {
  const element = document.getElementById(id);
  return element ? element.value : null;
}

/**
 * Helper: Set input value by ID
 */
function setInputValue(id, value) {
  const element = document.getElementById(id);
  if (element && value !== undefined && value !== null) {
    element.value = value;
  }
}

/**
 * Helper: Get select value by ID
 */
function getSelectValue(id) {
  const element = document.getElementById(id);
  return element ? element.value : null;
}

/**
 * Helper: Set select value by ID
 */
function setSelectValue(id, value) {
  const element = document.getElementById(id);
  if (element && value) {
    element.value = value;
  }
}

// Export functions for testing (if needed)
if (typeof module !== "undefined" && module.exports) {
  module.exports = {
    loadConfiguration,
    saveConfiguration,
    resetConfiguration,
    collectFormData,
  };
}
