#!/bin/sh
set -eu

# Build wheel and verify packaged resources
# Runs through project-env, unpacks into temp dir, verifies contents, cleans up

root=$(git rev-parse --show-toplevel)

# Create temp directory for unpacking (subshell-wrapped for isolation)
(
  tmpdir=$(mktemp -d)
  trap 'rm -rf "$tmpdir"' EXIT

  # Build wheel and sdist using project-env, into a temp dir so nothing lands
  # in the real dist/ directory.
  cd "$root"
  ./.agents/scripts/project-env uv build -q --out-dir "$tmpdir/dist"

  # Find the built wheel (most recently modified)
  wheel_file=$(find "$tmpdir/dist" -maxdepth 1 -name '*.whl' -type f -print -quit)
  if [ -z "$wheel_file" ]; then
    printf 'package-check: no wheel found in dist/\n' >&2
    exit 1
  fi
  if ! find "$tmpdir/dist" -maxdepth 1 -name '*.tar.gz' -type f | grep -q .; then
    printf 'package-check: no source distribution found in dist/\n' >&2
    exit 1
  fi

  # Unpack wheel
  cd "$tmpdir"
  unzip -q "$wheel_file"

  # Verify every resource read by runtime code is present in the package.
  errors=0
  required_files='dj_digger/analysis.toml
dj_digger/schema-bundle.json
dj_digger/core/schemas/tracks.schema.json
dj_digger/core/schemas/curation-result.schema.json
dj_digger/core/schemas/dj-set.schema.json
dj_digger/core/schemas/library-artifacts.schema.json
dj_digger/core/schemas/snapshot-manifest.schema.json
dj_digger/core/schemas/dj-analysis.schema.json
dj_digger/core/schemas/dj-sections.schema.json
dj_digger/core/schemas/dj-analysis-run.schema.json
dj_digger/core/catalog/sql/catalog.sql
dj_digger/core/catalog/sql/migrate-20260827105404.sql
dj_digger/core/catalog/sql/migrate-20260827225144.sql
dj_digger/core/catalog/sql/migrate-20260828150213.sql
dj_digger/core/catalog/sql/migrate-20260905221652.sql
dj_digger/core/catalog/sql/migrate-20260907063758.sql'
  while IFS= read -r required; do
    [ -z "$required" ] && continue
    if [ ! -f "$required" ]; then
      printf 'package-check: required resource missing: %s\n' "$required" >&2
      errors=1
    fi
  done <<EOF
$required_files
EOF
  [ "$errors" -eq 0 ] || exit "$errors"

  # Run the installed wheel through its public console entry point from a
  # directory that contains neither the checkout nor source files.
  package_workspace="$tmpdir/runtime"
  mkdir -p "$package_workspace/music" "$package_workspace/exports"
  cat > "$package_workspace/config.toml" <<'EOF'
[workspace]
database = "catalog.sqlite"
exports = "exports"

[[library.sources]]
id = "disabled"
path = "music"
set_eligible = false
analyze = false
enabled = false
EOF
  cd "$package_workspace"
  "$root/.agents/scripts/project-env" uvx --from "$wheel_file" dj-digger --help >/dev/null
  "$root/.agents/scripts/project-env" uvx --from "$wheel_file" dj-digger doctor \
    --config "$package_workspace/config.toml" --json >/dev/null
)
