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

DIR="$(cd "$(dirname "$0")" && pwd)"
source "$DIR/runtime.sh"

# --- Load types first (ops may depend on them) ---
echo "=== Loading types ==="
source "$DIR/ops/types.op.sh"
load_type "@type.port";        echo "  port"
load_type "@type.semver";      echo "  semver"
load_type "@type.datacenter";  echo "  datacenter"

# --- Load ops ---
echo ""
echo "=== Loading ops ==="
source "$DIR/ops/git.sign.op.sh"
load_op "@operation.git.sign"; echo "  git.sign"

source "$DIR/ops/deploy.op.sh"
load_op "@operation.deploy.service"; echo "  deploy.service"

source "$DIR/ops/condition.eq.op.sh"
load_op "@operation.condition.eq"; echo "  condition.eq"

source "$DIR/ops/release.op.sh"
load_op "@operation.release.tag"; echo "  release.tag"

# --- Registry dump ---
echo ""
dump_registry

# --- Dispatch tests ---
echo ""
echo "=== Dispatch: git.sign ==="
result=$(dispatch "git.sign" "do" "my-gpg-key")
echo "  $result"

echo ""
echo "=== Dispatch: git.sign @undo ==="
result=$(dispatch "git.sign" "undo")
echo "  $result"

echo ""
echo "=== Dispatch: deploy.service ==="
result=$(dispatch "deploy.service" "do" "api-server" "v2.1.0" "8443")
echo "  $result"

echo ""
echo "=== Dispatch: condition.eq (match) ==="
result=$(dispatch "condition.eq" "do" "hello" "hello")
echo "  $result"

echo ""
echo "=== Dispatch: condition.eq (no match) ==="
result=$(dispatch "condition.eq" "do" "hello" "world")
echo "  $result"

echo ""
echo "=== Dispatch: release.tag ==="
result=$(dispatch "release.tag" "do" "1.4.2" "production")
echo "  $result"

# --- Type constructor tests ---
echo ""
echo "=== Type constructors: defaults (zero-arg) ==="
echo "  @port:       $(@port)"
echo "  @datacenter: $(@datacenter)"

echo ""
echo "=== Type constructors: value mode ==="
echo "  @port 8080:             $(@port 8080)"
echo "  @semver 1.2.3:          $(@semver "1.2.3")"
echo "  @datacenter production: $(@datacenter "production")"

echo ""
echo "=== Type validation: rejections ==="
@port 99999 2>/dev/null       && echo "  FAIL: port 99999"       || echo "  PASS: port 99999 rejected"
@semver "not.a.ver" 2>/dev/null && echo "  FAIL: semver not.a.ver" || echo "  PASS: semver not.a.ver rejected"
@datacenter "mars" 2>/dev/null  && echo "  FAIL: dc mars"          || echo "  PASS: datacenter mars rejected"

# --- Collision check ---
echo ""
echo "=== No leaked inner functions ==="
ok=true
for fn in @do @undo @is-done @is; do
    declare -F "$fn" &>/dev/null && { echo "  LEAK: $fn"; ok=false; }
done
$ok && echo "  PASS"
