import type maplibregl from 'maplibre-gl';

/**
 * Ocean 스타일 레이어를 source-layer 기반으로 동적 탐색.
 * MapTiler Ocean 스타일의 레이어 ID는 버전에 따라 변경될 수 있으므로,
 * ID 하드코딩 대신 source-layer + type 조합으로 필터링.
 */

interface OceanLayerMap {
  depthFill: string[];     // source-layer: contour/depth, type: fill
  contourLine: string[];   // source-layer: contour_line/contour, type: line
  depthLabel: string[];    // source-layer: contour_line, type: symbol
  hillshade: string[];     // type: hillshade
  landformLabel: string[]; // source-layer: landform, type: symbol
  background: string[];    // type: background
  allSymbol: string[];     // type: symbol (라벨 언어 전환용)
}

export function discoverOceanLayers(map: maplibregl.Map): OceanLayerMap {
  const result: OceanLayerMap = {
    depthFill: [],
    contourLine: [],
    depthLabel: [],
    hillshade: [],
    landformLabel: [],
    background: [],
    allSymbol: [],
  };

  let layers: unknown[];
  try {
    const style = map.getStyle();
    layers = style && Array.isArray(style.layers) ? style.layers : [];
  } catch {
    return result;
  }

  for (const layer of layers) {
    const spec = layer as Record<string, unknown>;
    const id = spec.id as string | undefined;
    const type = spec.type as string | undefined;
    const sourceLayer = spec['source-layer'] as string | undefined;
    if (!id || !type) continue;

    if (type === 'background') {
      result.background.push(id);
      continue;
    }

    if (type === 'hillshade') {
      result.hillshade.push(id);
      continue;
    }

    if (type === 'symbol') {
      result.allSymbol.push(id);
      if (sourceLayer === 'landform' || sourceLayer === 'landform_point') {
        result.landformLabel.push(id);
      } else if (sourceLayer === 'contour_line' || sourceLayer === 'contour') {
        result.depthLabel.push(id);
      }
      continue;
    }

    if (type === 'fill' && (sourceLayer === 'contour' || sourceLayer === 'depth')) {
      result.depthFill.push(id);
      continue;
    }

    if (type === 'line' && (sourceLayer === 'contour_line' || sourceLayer === 'contour')) {
      result.contourLine.push(id);
      continue;
    }
  }

  return result;
}
