#!/usr/bin/env bash
# run_script.sh — Compile and run a standalone .cs file with OpenXML SDK.
# Usage: bash scripts/run_script.sh path/to/script.cs
set -euo pipefail

SCRIPTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(cd "$SCRIPTS/.." && pwd)"

if [ $# -lt 1 ]; then
  echo "Usage: bash scripts/run_script.sh <script.cs>" >&2
  exit 1
fi

SCRIPT_PATH="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
if [ ! -f "$SCRIPT_PATH" ]; then
  echo "Error: file not found: $1" >&2
  exit 1
fi

TMPDIR="${SKILL_DIR}/scripts/.run_tmp"
rm -rf "$TMPDIR"
mkdir -p "$TMPDIR"

cat > "$TMPDIR/RunScript.csproj" << 'CSPROJ'
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
  </ItemGroup>
</Project>
CSPROJ

# Strip #r directives (dotnet-script syntax not needed in regular project)
sed 's/^#r .*$//' "$SCRIPT_PATH" > "$TMPDIR/Program.cs"

cd "$TMPDIR"
dotnet run --project RunScript.csproj 2>&1
EXIT_CODE=$?

rm -rf "$TMPDIR"
exit $EXIT_CODE
