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

# .NET Starter Validation Script
#
# Purpose:
#   Validate that a .NET SDK installation is usable for local development.
#   The script checks for the dotnet CLI, prints version information, creates
#   a temporary console app, builds it, runs it, and cleans up afterward.
#
# Safe defaults:
#   - No destructive actions against existing projects
#   - Uses a temporary working directory
#   - No credentials or environment-specific endpoints
#
# Usage:
#   ./dotnet-starter-validation.sh
#   ./dotnet-starter-validation.sh [project_name]
#
# Example:
#   ./dotnet-starter-validation.sh HelloDotNet

PROJECT_NAME="${1:-HelloDotNet}"
WORKDIR=""

cleanup() {
  if [[ -n "${WORKDIR}" && -d "${WORKDIR}" ]]; then
    rm -rf "${WORKDIR}"
  fi
}
trap cleanup EXIT

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Error: required command '$1' was not found in PATH." >&2
    exit 1
  fi
}

validate_project_name() {
  # Keep the project name simple and filesystem-safe.
  if [[ ! "${PROJECT_NAME}" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]]; then
    echo "Error: project name must start with a letter and contain only letters, numbers, underscores, or hyphens." >&2
    exit 1
  fi
}

main() {
  validate_project_name
  require_command dotnet

  echo "== .NET environment check =="
  echo
  echo "dotnet --version:"
  dotnet --version
  echo
  echo "dotnet --info:"
  dotnet --info
  echo

  WORKDIR="$(mktemp -d)"
  echo "Using temporary workspace: ${WORKDIR}"
  cd "${WORKDIR}"

  echo
  echo "== Creating console project =="
  dotnet new console -n "${PROJECT_NAME}" >/dev/null
  cd "${PROJECT_NAME}"

  echo
  echo "== Building project =="
  dotnet build

  echo
  echo "== Running project =="
  dotnet run

  echo
  echo "Validation complete: SDK install, template creation, build, and run all succeeded."
  echo "Temporary files will be removed automatically."
}

main "$@"