#!/bin/bash
# Build the composite solver package.
#
# This script is invoked from the package root. It first builds every nested
# solver referenced by order.json, then configures CMake to compile the fixed
# profiler/dispatcher core and all linked matcher translation units.

set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
ORDER_JSON="$ROOT/order.json"

if [[ ! -f "$ORDER_JSON" ]]; then
    echo "missing order.json" >&2
    exit 2
fi

NESTED_SOLVERS_FILE="$ROOT/.build_nested_solvers.txt"
python3 - "$ORDER_JSON" > "$NESTED_SOLVERS_FILE" <<'PY'
import json
import re
import sys

path = sys.argv[1]
with open(path, "r", encoding="utf-8") as f:
    data = json.load(f)

names = list(data.get("solver_order", []))
fallback = data.get("fallback_solver")
if fallback and fallback not in names:
    names.append(fallback)

seen = set()
for name in names:
    if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
        raise SystemExit(f"invalid solver name in order.json: {name!r}")
    if name in seen:
        continue
    seen.add(name)
    print(name)
PY

while IFS= read -r name; do
    [[ -n "$name" ]] || continue
    pkg="$ROOT/solvers/$name/solver"
    if [[ ! -d "$pkg" ]]; then
        echo "missing nested solver package: solvers/$name/solver" >&2
        exit 2
    fi
    if [[ -f "$pkg/build.sh" ]]; then
        echo "building nested solver: $name"
        (cd "$pkg" && chmod +x ./build.sh && ./build.sh)
    else
        chmod +x "$pkg/solver"
    fi
    if [[ ! -x "$pkg/solver" ]]; then
        echo "nested solver did not produce executable: solvers/$name/solver/solver" >&2
        exit 2
    fi
done < "$NESTED_SOLVERS_FILE"

export CC="${CC:-clang}"
export CXX="${CXX:-clang++}"

if [[ "$(uname -m)" == "x86_64" ]]; then
    export CXXFLAGS="${CXXFLAGS:-} -march=icelake-server -mtune=icelake-server"
fi

BUILD_DIR="${LYMPHOSAT_COMPOSITE_BUILD_DIR:-$ROOT/.build}"

cmake -S "$ROOT" -B "$BUILD_DIR" -DCMAKE_BUILD_TYPE=Release

if [[ -n "${CMAKE_BUILD_PARALLEL_LEVEL:-}" ]]; then
    cmake --build "$BUILD_DIR" --target lymphosat_composite --parallel "$CMAKE_BUILD_PARALLEL_LEVEL"
else
    cmake --build "$BUILD_DIR" --target lymphosat_composite
fi

chmod +x "$ROOT/solver"
echo "composite solver built at $ROOT/solver"
