type RuntimeConfig = {
  BACKEND_URL?: string;
  AGENT_URL?: string;
  MAP_URL?: string;
  MAP_WORKSPACE?: string;
  MAP_EXTENT?: number[] | string;
  NETWORK_NAME?: string;
  MAPBOX_TOKEN?: string;
  TIANDITU_TOKEN?: string;
};

declare global {
  interface Window {
    __TJWATER_RUNTIME_CONFIG__?: RuntimeConfig;
  }
}

const runtimeConfig =
  typeof window === "undefined" ? {} : window.__TJWATER_RUNTIME_CONFIG__ ?? {};

const parseMapExtent = (value: RuntimeConfig["MAP_EXTENT"]): number[] => {
  if (Array.isArray(value)) {
    return value;
  }

  if (typeof value === "string" && value.trim()) {
    return value.split(",").map(Number);
  }

  return [13508849, 3608036, 13555781, 3633813];
};

export const config = {
  BACKEND_URL: runtimeConfig.BACKEND_URL || "http://127.0.0.1:8000",
  AGENT_URL: runtimeConfig.AGENT_URL || "http://127.0.0.1:8788",
  MAP_URL: runtimeConfig.MAP_URL || "http://127.0.0.1:8080/geoserver",
  MAP_WORKSPACE: runtimeConfig.MAP_WORKSPACE || "tjwater",
  MAP_EXTENT: parseMapExtent(runtimeConfig.MAP_EXTENT),
  MAP_DEFAULT_STYLE: {
    "stroke-width": 3,
    "stroke-color": "rgba(51, 153, 204, 0.9)",
    "circle-fill-color": "rgba(255,138, 92,0.8)",
    "circle-stroke-color": "rgba(255,138, 92,0.9)",
    "circle-radius": [
      "interpolate",
      ["linear"],
      ["zoom"],
      12,
      1, // 在缩放级别 12 时，圆形半径为 1px
      24,
      8, // 在缩放级别 24 时，圆形半径为 8px
    ],
  },
  MAP_AVAILABLE_LAYERS: [
    "junctions",
    "pipes",
    "valves",
    "reservoirs",
    "pumps",
    "tanks",
    "scada",
  ],
};
export let NETWORK_NAME = runtimeConfig.NETWORK_NAME || "tjwater";

export const setNetworkName = (name: string) => {
  NETWORK_NAME = name;
};

export const setMapWorkspace = (workspace: string) => {
  config.MAP_WORKSPACE = workspace;
};

export const setMapExtent = (extent: number[]) => {
  config.MAP_EXTENT = extent;
};

export const MAPBOX_TOKEN = runtimeConfig.MAPBOX_TOKEN || "";
export const TIANDITU_TOKEN = runtimeConfig.TIANDITU_TOKEN || "";
export const PROJECT_TITLE =
  process.env.PROJECT_TITLE || "TJWater 智慧水务平台";
export const META_DATA = {
  title: PROJECT_TITLE,
  description: PROJECT_TITLE,
  icons: {
    icon: "/favicon.ico",
  },
};

export default config;
