# catalog/operations/vector/merge_by_rules.yaml

id: vector_merge_by_rules
name: Merge Features by Rules
description: >
  Merge vector features based on configurable rules including name matching,
  adjacency, and explicit merge specifications. Used to combine HUC12
  polygons into larger drainage units based on naming conventions.
version: 1.0.0
category: vector
type: vector-to-vector
default_implementation: native

inputs:
  - name: features
    type: vector
    format: geojson
    geometry: Polygon
    description: Input polygon features to merge
    required: true

# Structural op — operates on any vector polygons via name/adjacency rules.
requires: {}

outputs:
  - name: merged
    type: vector
    format: geojson
    geometry: Polygon
    description: Merged polygon features

  - name: merge_log
    type: stats
    format: json
    description: Log of which features were merged together
    required: false

params:
  merge_by_group:
    type: boolean
    default: true
    description: >
      Merge features that share the same group_id (from group_by_name).
      Requires features to have group_id attribute.

  require_adjacency:
    type: boolean
    default: true
    description: >
      Only merge features that are spatially adjacent (touching).
      If false, may create multipolygons from disjoint features.

  explicit_merges:
    type: array
    default: []
    description: >
      List of explicit merge rules as objects with 'target' (name to merge into)
      and 'sources' (list of names to merge). Takes precedence over automatic rules.

  exclude_patterns:
    type: array
    default: []
    description: >
      Regex patterns for names to exclude from merging.
      Features matching these patterns remain separate.

  name_column:
    type: string
    default: name
    description: Column containing feature name for rule matching

  output_name_column:
    type: string
    default: merged_name
    description: Column for the merged feature's name

  aggregation:
    type: string
    default: '{"area_km2": "sum", "huc12_count": "count"}'
    description: >
      JSON string defining how to aggregate numeric columns when merging.
      Keys are column names, values are aggregation functions (sum, mean, min, max, count).

cache_policy:
  ttl_days: 30
  invalidate_on: [source_update, param_change]

# backends: audited 2026-08-14 (defect 50). A key means a runtime that DISPATCHES this op —
# folia-engine `dispatch_op` (products/sdk/folia-engine/src/lib.rs), a `registerOp`/OP_TABLE
# entry in packages/compute, `_BUILTIN_OP_MAP` in folia/compute.py, or a backend manifest
# (folia/backends/*/backend.yaml).
backends:
  python:
    function: geo.vector.merge_by_rules
    dispatch: folia/compute.py _BUILTIN_OP_MAP

display_hints:
  map:
    renderer: maplibre
    type: fill
    paint:
      fill-color: "rgba(138, 43, 226, 0.3)"
      fill-outline-color: "#8A2BE2"

ui:
  icon: git-merge
  color: "#8A2BE2"
