#!/bin/sh
set -ex

WORK_DIR=$(mktemp -d)
trap 'rm -rf "$WORK_DIR"' EXIT
cd "$WORK_DIR"

# Create a minimal Starlark rule
cat > check.bzl <<'EOF'
"""A minimal rule for testing Stardoc."""

def _check_rule_impl(ctx):
    return []

check_rule = rule(
    implementation = _check_rule_impl,
    doc = "This is a dummy check rule to verify stardoc doc generation.",
    attrs = {
        "message": attr.string(doc = "A greeting message.", mandatory = True),
    },
)
EOF

# Create BUILD file using stardoc
cat > BUILD <<'EOF'
load("@io_bazel_skydoc//stardoc:stardoc.bzl", "stardoc")

stardoc(
    name = "check_doc",
    input = "check.bzl",
    out = "check_doc.md",
)
EOF

# Create WORKSPACE file
cat > WORKSPACE <<'EOF'
workspace(name = "test_stardoc")

local_repository(
    name = "io_bazel_skydoc",
    path = "/usr/share/bazel/tools/stardoc",
)
EOF

# Create MODULE.bazel file for Bzlmod
cat > MODULE.bazel <<'EOF'
module(name = "test_stardoc", version = "0.1")

bazel_dep(name = "stardoc", version = "0.8.1", repo_name = "io_bazel_skydoc")
EOF

# Run Bazel to generate documentation
bazel build \
    --override_module=stardoc=/usr/share/bazel/tools/stardoc \
    --java_runtime_version=local_jdk \
    --tool_java_runtime_version=local_jdk \
    --javabase=@bazel_tools//tools/jdk:local_jdk \
    --host_javabase=@bazel_tools//tools/jdk:local_jdk \
    //:check_doc

# Verify generated markdown file
test -f bazel-bin/check_doc.md
cat bazel-bin/check_doc.md
grep -q "This is a dummy check rule to verify stardoc doc generation." bazel-bin/check_doc.md
grep -q "greeting message" bazel-bin/check_doc.md

echo "Stardoc functional test passed successfully!"
