import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import axios from 'axios';

interface ServerConfig {
  id: string;
  name: string;
  url: string;
  pythonServiceUrl?: string;
  isDefault?: boolean;
}

const STORAGE_KEY = 'server_configs';
const CURRENT_SERVER_KEY = 'current_server';
const SINGLE_SERVER_ID = 'server_default';

export const useServerStore = defineStore('server', () => {
  const servers = ref<ServerConfig[]>([]);
  const currentServerId = ref<string | null>(null);
  const connectionStatus = ref<'connected' | 'disconnected' | 'checking'>('disconnected');
  const lastConnectionError = ref<string | null>(null);

  const currentServer = computed(() => 
    servers.value.find(s => s.id === currentServerId.value)
  );

  const isConfigured = computed(() => !!currentServer.value);

  // 加载配置
  function loadConfig() {
    const savedServers = localStorage.getItem(STORAGE_KEY);
    const savedCurrent = localStorage.getItem(CURRENT_SERVER_KEY);
    
    if (savedServers) {
      servers.value = JSON.parse(savedServers);
    }
    if (savedCurrent) {
      currentServerId.value = savedCurrent;
    }
  }

  // 保存配置
  function saveConfig() {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(servers.value));
    if (currentServerId.value) {
      localStorage.setItem(CURRENT_SERVER_KEY, currentServerId.value);
    }
  }

  // 添加服务器
  function addServer(config: Omit<ServerConfig, 'id'>) {
    const id = `server_${Date.now()}`;
    const server: ServerConfig = { ...config, id };
    servers.value.push(server);
    
    if (servers.value.length === 1 || config.isDefault) {
      currentServerId.value = id;
    }
    
    saveConfig();
    return server;
  }

  // 更新服务器
  function updateServer(id: string, config: Partial<ServerConfig>) {
    const index = servers.value.findIndex(s => s.id === id);
    if (index !== -1) {
      servers.value[index] = { ...servers.value[index], ...config };
      saveConfig();
    }
  }

  // 删除服务器
  function removeServer(id: string) {
    const index = servers.value.findIndex(s => s.id === id);
    if (index !== -1) {
      servers.value.splice(index, 1);
      if (currentServerId.value === id) {
        currentServerId.value = servers.value[0]?.id || null;
      }
      saveConfig();
    }
  }

  // 切换当前服务器
  function setCurrentServer(id: string) {
    if (servers.value.find(s => s.id === id)) {
      currentServerId.value = id;
      saveConfig();
    }
  }

  // 单服务器模式：覆盖保存一个服务器配置并设为当前，Python 服务地址也存本地
  function setSingleServer(config: { url: string; name?: string; pythonServiceUrl?: string }) {
    const url = config.url.replace(/\/$/, '');
    const name = (config.name || '').trim() || '服务器';
    const pythonServiceUrl = config.pythonServiceUrl?.replace(/\/$/, '') || undefined;
    servers.value = [{ id: SINGLE_SERVER_ID, name, url, pythonServiceUrl, isDefault: true }];
    currentServerId.value = SINGLE_SERVER_ID;
    saveConfig();
  }

  // 检查服务器连接
  async function checkConnection(url?: string): Promise<boolean> {
    const targetUrl = url || currentServer.value?.url;
    if (!targetUrl) return false;

    lastConnectionError.value = null;
    connectionStatus.value = 'checking';
    try {
      const electronApi = (window as any)?.electronAPI;
      if (electronApi?.testServerConnection) {
        const result = await electronApi.testServerConnection(targetUrl);
        if (result?.ok) {
          connectionStatus.value = 'connected';
          return true;
        }
        lastConnectionError.value = String(result?.error || '连接失败');
        connectionStatus.value = 'disconnected';
        return false;
      }

      const response = await axios.get(`${targetUrl}/api/health`, { timeout: 5000 });
      connectionStatus.value = response.data?.status === 'ok' ? 'connected' : 'disconnected';
      return connectionStatus.value === 'connected';
    } catch (e: any) {
      lastConnectionError.value = String(e?.message || '连接失败');
      connectionStatus.value = 'disconnected';
      return false;
    }
  }

  return {
    servers,
    currentServer,
    currentServerId,
    connectionStatus,
    lastConnectionError,
    isConfigured,
    loadConfig,
    addServer,
    updateServer,
    removeServer,
    setCurrentServer,
    setSingleServer,
    checkConnection,
  };
});
