#!/usr/bin/env bash
set -euo pipefail

if [ "$#" -ne 1 ]; then
  echo "usage: $0 <name>" >&2
  exit 1
fi

ROOT="$(cd "$(dirname "$0")" && pwd)"
NAME="$1"

if [[ ! "$NAME" =~ ^[A-Za-z0-9][A-Za-z0-9_-]*$ ]]; then
  echo "invalid package name: $NAME" >&2
  exit 1
fi

MODULE_NAME="${NAME//-/_}"
TARGET_DIR="$ROOT/tentacles/$NAME"
DIST_DIR="$TARGET_DIR/dist"

mkdir -p "$TARGET_DIR/$MODULE_NAME" "$DIST_DIR"

python3 - "$ROOT" "$TARGET_DIR" "$NAME" "$MODULE_NAME" <<'PY'
from pathlib import Path
import sys

root = Path(sys.argv[1])
target_dir = Path(sys.argv[2])
package_name = sys.argv[3]
module_name = sys.argv[4]

def render(template_name: str) -> str:
    text = (root / "_template" / template_name).read_text(encoding="utf-8")
    return text.replace("__PACKAGE_NAME__", package_name).replace("__MODULE_NAME__", module_name)

(target_dir / "setup.py").write_text(render("setup.py"), encoding="utf-8")
(target_dir / module_name / "__init__.py").write_text(render("__init__.py"), encoding="utf-8")
(target_dir / "README.md").write_text(
    f"# {package_name}\n\nThin wrapper around the shared MCP server.\n",
    encoding="utf-8",
)
PY

cd "$TARGET_DIR"

python3 setup.py sdist >/dev/null
if python3 -c "import wheel" >/dev/null 2>&1; then
  python3 setup.py bdist_wheel >/dev/null
fi

if [ -n "${TWINE_USERNAME:-}" ] && [ -n "${TWINE_PASSWORD:-}" ] && command -v twine >/dev/null 2>&1; then
  python3 -m twine upload dist/*
fi

echo "$TARGET_DIR"
