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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
FIXTURE_ROOT="${FIXTURE_ROOT:-$REPO_ROOT/.tmp/m015-fixture}"
API_PORT="${API_PORT:-5202}"
API_BASE="http://localhost:${API_PORT}/api"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

mkdir -p "$FIXTURE_ROOT"

echo "[m015] creating clean hostile-test db under $FIXTURE_ROOT"
dotnet run --project "$REPO_ROOT/tools/hostile-fixture-db/HostileFixtureDb.csproj" -- "$FIXTURE_ROOT" > "$TMP_DIR/db.json"
python3 - <<'PY' "$TMP_DIR/db.json"
import json, sys
payload=json.load(open(sys.argv[1]))
required={'Companies','JobApplications','Correspondences','Attachments','RuleSettings','AspNetUsers'}
missing=sorted(required-set(payload['tables']))
if missing:
    raise SystemExit(f"missing tables after fixture db init: {', '.join(missing)}")
print('[m015] db tables ok')
PY

echo "[m015] ready to start API with:"
echo "  Data__Root=$FIXTURE_ROOT ASPNETCORE_ENVIRONMENT=Development dotnet run --project JobTrackerApi/JobTrackerApi.csproj"
echo "[m015] API base: $API_BASE"
