#!/usr/bin/env bash
#
# build-windows-client.sh — build the Windows WinForms client and stage a
# runnable folder into dist/windows-client/.
#
# Two steps:
#   1. Build the native voicecat.dll via the `windows-client` CMake preset
#      (MinGW, static runtime — no libgcc_s_seh-1.dll / libstdc++-6.dll deps).
#   2. `dotnet publish` the C# app (clients/windows/VoiceCat.App). The app's
#      Directory.Build.props copies voicecat.dll into the output automatically.
#
# The staged folder contains VoiceCat.App.exe + voicecat.dll + all .NET deps,
# ready to run. By default it is framework-dependent (needs the .NET 10 runtime
# installed); pass --self-contained for a folder that runs without .NET.
#
# Usage:
#   scripts/build-windows-client.sh                # build + stage into ./dist/windows-client
#   scripts/build-windows-client.sh --dist /out
#   scripts/build-windows-client.sh --no-configure # skip cmake configure (DLL step)
#   scripts/build-windows-client.sh --self-contained
#   scripts/build-windows-client.sh -h|--help
#
# Windows only (MSYS2/MinGW). Requires VCPKG_ROOT and the .NET 10 SDK.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VC_SCRIPT_NAME="build-windows-client"
source "$SCRIPT_DIR/common.sh"

DO_CONFIGURE=true
SELF_CONTAINED=false
while [[ $# -gt 0 ]]; do
    case "$1" in
        --dist)           vc_set_dist "$2"; shift 2 ;;
        --no-configure)   DO_CONFIGURE=false; shift ;;
        --self-contained) SELF_CONTAINED=true; shift ;;
        -h|--help)        vc_print_help "$0"; exit 0 ;;
        *) vc_die "unknown arg: $1 (try --help)" ;;
    esac
done

vc_require_windows
vc_log "dist dir: $VC_DIST_DIR"
vc_resolve_vcpkg_root windows-client

vc_step "build native DLL (preset: windows-client)"
if $DO_CONFIGURE; then
    cmake --preset windows-client
fi
cmake --build --preset windows-client
DLL="$VC_REPO_ROOT/build/windows-client/bin/voicecat.dll"
[[ -f "$DLL" ]] || vc_die "expected output not found: $DLL"
vc_ok "voicecat.dll -> $DLL ($(vc_file_size "$DLL") bytes)"

vc_step "publish C# app (dotnet publish)"
APP_PROJ="$VC_REPO_ROOT/clients/windows/VoiceCat.App/VoiceCat.App.csproj"
PUBLISH_DIR="$VC_REPO_ROOT/build/windows-client/publish"
rm -rf "$PUBLISH_DIR"
mkdir -p "$PUBLISH_DIR"

PUBLISH_ARGS=(dotnet publish "$APP_PROJ" -c Release -o "$PUBLISH_DIR")
if $SELF_CONTAINED; then
    PUBLISH_ARGS+=( -r win-x64 --self-contained true )
fi
"${PUBLISH_ARGS[@]}"
APP_EXE="$PUBLISH_DIR/VoiceCat.App.exe"
[[ -f "$APP_EXE" ]] || vc_die "publish output missing VoiceCat.App.exe in $PUBLISH_DIR"

vc_step "stage -> $VC_DIST_DIR/windows-client"
STAGE="$(vc_dist_subdir windows-client)"
cp -R "$PUBLISH_DIR/." "$STAGE/"
vc_ok "VoiceCat.App.exe + deps -> $STAGE (voicecat.dll included)"
vc_ok "done -> $STAGE"
