#!/usr/bin/env bash
# Article 03: create → insert → flush → observe Growing/Sealed segment state.
# Requires a reachable Milvus 2.6.x (typically Docker standalone, ≥4 GiB RAM).
# This writing host (2 GiB, no Docker) cannot run the stack; script exits 2 with
# a clear boundary when MILVUS_URI is unset or pymilvus cannot connect.
set -euo pipefail

echo "# host: $(uname -a)"
echo "# mem_available_kb: $(awk '/MemAvailable/ {print $2}' /proc/meminfo 2>/dev/null || echo n/a)"
echo "# nproc: $(nproc 2>/dev/null || echo n/a)"

if ! command -v docker >/dev/null 2>&1; then
  echo "BOUNDARY: docker not found on this host."
  echo "To reproduce elsewhere:"
  echo "  1. Start Milvus 2.6.x standalone (official docker-compose, ≥4 GiB)."
  echo "  2. export MILVUS_URI=http://127.0.0.1:19530"
  echo "  3. pip install 'pymilvus>=2.6,<2.7'"
  echo "  4. Re-run this script."
  exit 2
fi

if [[ -z "${MILVUS_URI:-}" ]]; then
  echo "BOUNDARY: MILVUS_URI unset; refusing to invent segment states."
  echo "Example: export MILVUS_URI=http://127.0.0.1:19530"
  exit 2
fi

python3 - <<'PY'
import os, sys, time
uri = os.environ["MILVUS_URI"]
try:
    from pymilvus import (
        MilvusClient,
        DataType,
    )
except ImportError:
    print("ERROR: pymilvus not installed", file=sys.stderr)
    sys.exit(2)

client = MilvusClient(uri=uri)
name = "ve_s_tier_seg_demo"
if client.has_collection(name):
    client.drop_collection(name)

schema = client.create_schema(auto_id=True, enable_dynamic_field=False)
schema.add_field("id", DataType.INT64, is_primary=True, auto_id=True)
schema.add_field("vec", DataType.FLOAT_VECTOR, dim=8)
index_params = client.prepare_index_params()
index_params.add_index(field_name="vec", index_type="FLAT", metric_type="L2")
client.create_collection(collection_name=name, schema=schema, index_params=index_params)

rows = [{"vec": [float(i)] * 8} for i in range(100)]
client.insert(collection_name=name, data=rows)
print("after_insert: ok rows=100")
# flush to encourage Sealed transition (API / version dependent naming)
client.flush(collection_name=name)
time.sleep(1)
# Best-effort segment listing across pymilvus versions
segs = None
for attr in ("get_persistent_segment_info", "get_segments_info", "list_segments"):
    fn = getattr(client, attr, None)
    if callable(fn):
        try:
            segs = fn(collection_name=name)
            print(f"segment_api={attr}")
            break
        except Exception as e:
            print(f"segment_api={attr} failed: {e}")
if segs is None:
    # fallback: describe collection only
    print("segment_list: unavailable via this pymilvus client; describe_collection follows")
    print(client.describe_collection(collection_name=name))
else:
    print("segments:", segs)
client.drop_collection(name)
print("done")
PY
