/**
 * 文件职责：配送区域 GeoJSON 工具。
 * 1. 负责 Polygon FeatureCollection 与坐标数组互转。
 * 2. 提供绘制结果统计能力，供 UI 展示已绘制数量。
 */

export type LngLatTuple = [number, number];

type JsonRecord = Record<string, unknown>;

function isFiniteNumber(value: unknown): value is number {
  return typeof value === 'number' && Number.isFinite(value);
}

function isLngLatTuple(value: unknown): value is LngLatTuple {
  if (!Array.isArray(value) || value.length < 2) return false;
  const [lng, lat] = value;
  if (!isFiniteNumber(lng) || !isFiniteNumber(lat)) return false;
  return lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90;
}

function closePolygonRing(points: LngLatTuple[]) {
  if (points.length < 3) return [];
  const normalized = points.map(([lng, lat]) => [lng, lat] as LngLatTuple);
  const first = normalized[0];
  const last = normalized[normalized.length - 1];
  if (!first || !last) return [];
  if (first[0] !== last[0] || first[1] !== last[1]) {
    normalized.push([first[0], first[1]]);
  }
  return normalized;
}

/**
 * 将多边形坐标序列转换为 FeatureCollection 字符串。
 */
export function stringifyPolygonGeoJson(polygons: LngLatTuple[][]) {
  const features = polygons
    .map((points) => closePolygonRing(points))
    .filter((ring) => ring.length >= 4)
    .map((ring) => ({
      type: 'Feature',
      geometry: {
        type: 'Polygon',
        coordinates: [ring],
      },
      properties: {},
    }));

  return JSON.stringify({
    type: 'FeatureCollection',
    features,
  });
}

/**
 * 从 FeatureCollection 中解析外环点位，供地图回显与编辑。
 */
export function parsePolygonGeoJson(raw: string) {
  if (!raw) return [] as LngLatTuple[][];
  try {
    const parsed = JSON.parse(raw) as JsonRecord;
    if (parsed.type !== 'FeatureCollection') return [] as LngLatTuple[][];

    const features = parsed.features;
    if (!Array.isArray(features)) return [] as LngLatTuple[][];

    const polygons: LngLatTuple[][] = [];
    for (const feature of features) {
      const featureRecord =
        feature && typeof feature === 'object'
          ? (feature as JsonRecord)
          : undefined;
      const geometry =
        featureRecord?.geometry && typeof featureRecord.geometry === 'object'
          ? (featureRecord.geometry as JsonRecord)
          : undefined;
      if (!geometry || geometry.type !== 'Polygon') continue;

      const coordinates = geometry.coordinates;
      if (!Array.isArray(coordinates) || coordinates.length === 0) continue;

      const outerRing = coordinates[0];
      if (!Array.isArray(outerRing)) continue;
      const points = outerRing.filter((point) =>
        isLngLatTuple(point),
      ) as LngLatTuple[];
      if (points.length >= 4) {
        polygons.push(points.map(([lng, lat]) => [lng, lat]));
      }
    }

    return polygons;
  } catch {
    return [] as LngLatTuple[][];
  }
}

/**
 * 统计 GeoJSON 内有效 Polygon 数量。
 */
export function countPolygonsInGeoJson(raw: string) {
  return parsePolygonGeoJson(raw).length;
}
