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

script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
export BEAM_VLCKIT_PLATFORMS=tvos
export BEAM_VLCKIT_OUTPUT_BASENAME=inventory-tvos
# shellcheck source=common.sh
source "$script_dir/common.sh"

beam_assert_work_dir
trap beam_release_canonical_lock EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
beam_acquire_canonical_lock

grep -q '^BEAM_APPLETV_MODULE_INVENTORY_SHA256=PENDING_' "$beam_pins_file" || \
  beam_die "AppleTV inventory is already pinned; use build_all_platforms.sh"

"$script_dir/prepare_sources.sh"
"$script_dir/preflight.sh" tvos
rm -rf "$beam_vlckit_staging_dir"
mkdir -p "$beam_vlckit_staging_dir/logs"
cp "$beam_vlckit_source_metadata" "$beam_vlckit_staging_dir/SOURCE-MANIFEST.txt"

set +e
"$script_dir/build_platform.sh" tvos
status=$?
set -e
[[ $status -ne 0 ]] || beam_die "pending AppleTV pins unexpectedly allowed a final framework link"

evidence="$beam_vlckit_staging_dir/audit/modules/tvos/AppleTV"
for name in module-inventory.tsv included-lgpl-modules.tsv \
    excluded-gpl-modules.tsv approved-module-entries.tsv module-inventory-digests.txt; do
  [[ -s "$evidence/$name" ]] || beam_die "pending build did not produce $evidence/$name"
done
grep -q 'module inventory is not the reviewed pinned set' \
  "$beam_vlckit_staging_dir/logs/build-tvos.log" || \
  beam_die "tvOS build failed before the expected inventory review gate"

echo "AppleTV device/simulator inventory evidence is ready for independent review:"
echo "  $evidence"
echo "No TVVLCKit framework was linked and no VERIFIED marker was created."
