import type { GeoPoint } from "../model/mapTypes";

export function parseWktPolygon(wkt: string): GeoPoint[][] {
  const upper = wkt.trim().toUpperCase();

  if (upper.startsWith("MULTIPOLYGON")) {
    return parseMultiPolygon(wkt);
  }

  if (upper.startsWith("POLYGON")) {
    const ring = parseSinglePolygon(wkt);
    return ring ? [ring] : [];
  }

  return [];
}

function parseSinglePolygon(wkt: string): GeoPoint[] | null {
  const match = wkt.match(/POLYGON\s*\(\s*\(([^)]+)\)/i);
  if (!match) return null;
  return parseRing(match[1]);
}

function parseMultiPolygon(wkt: string): GeoPoint[][] {
  const rings: GeoPoint[][] = [];
  const inner = wkt.replace(/MULTIPOLYGON\s*\(/i, "").replace(/\)\s*$/, "");
  const polygonStrings = inner.match(/\(\s*\([^)]+\)\s*\)/g);
  if (!polygonStrings) return rings;

  for (const polygonStr of polygonStrings) {
    const ringMatch = polygonStr.match(/\(\s*\(([^)]+)\)/);
    if (ringMatch) {
      const ring = parseRing(ringMatch[1]);
      if (ring.length >= 3) {
        rings.push(ring);
      }
    }
  }

  return rings;
}

function parseRing(coordStr: string): GeoPoint[] {
  return coordStr
    .split(",")
    .map((pair) => {
      const parts = pair.trim().split(/\s+/);
      const lon = parseFloat(parts[0]);
      const lat = parseFloat(parts[1]);
      if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
      return { lon, lat };
    })
    .filter((point): point is GeoPoint => point !== null);
}
