#!/usr/bin/env bash
# inject.sh — Transpile a Push3 file and inject into OptimizerV3.sol
# Usage: bash inject.sh <push3_file> [optimizer_v3_sol]
# Default OptimizerV3.sol: onchain/src/OptimizerV3.sol (relative to repo root)
# Exit codes: 0=success, 1=transpile failed, 2=inject failed
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

PUSH3_FILE="${1:?Usage: inject.sh <push3_file> [optimizer_v3_sol]}"
OPTIMIZERV3_SOL="${2:-$REPO_ROOT/onchain/src/OptimizerV3.sol}"
TRANSPILER_OUT="$REPO_ROOT/onchain/src/OptimizerV3Push3.sol"

# Ensure transpiler deps
if [ ! -d "$SCRIPT_DIR/node_modules" ]; then
  (cd "$SCRIPT_DIR" && npm install --silent) || exit 1
fi

# 1. Transpile Push3 → OptimizerV3Push3.sol (full contract)
# Use tsx (not ts-node) — ts-node ESM resolution is broken on Node ≥22.
(cd "$SCRIPT_DIR" && npx tsx src/index.ts "$PUSH3_FILE" "$TRANSPILER_OUT") || exit 1

# 2. Extract function body and inject between BEGIN/END markers in OptimizerV3.sol
python3 - "$TRANSPILER_OUT" "$OPTIMIZERV3_SOL" <<'PYEOF' || exit 2
import sys

push3_path = sys.argv[1]
v3_path = sys.argv[2]

with open(push3_path) as f:
    push3 = f.read()

fn_start = push3.find("function calculateParams")
if fn_start == -1:
    sys.exit("calculateParams not found in OptimizerV3Push3")
brace_start = push3.find("{", fn_start)
body_start = push3.index("\n", brace_start) + 1

lines = push3[body_start:].split("\n")
body_lines = []
depth = 1
for line in lines:
    depth += line.count("{") - line.count("}")
    if depth <= 0:
        break
    body_lines.append(line)
else:
    sys.exit("error: calculateParams body: closing brace never found (EOF)")

body = "\n".join(body_lines)

with open(v3_path) as f:
    v3 = f.read()

begin_marker = "// ── BEGIN TRANSPILER OUTPUT"
end_marker = "// ── END TRANSPILER OUTPUT"
begin_idx = v3.find(begin_marker)
end_idx = v3.find(end_marker)
if begin_idx == -1 or end_idx == -1:
    sys.exit("markers not found in OptimizerV3.sol")

begin_line_end = v3.index("\n", begin_idx) + 1
with open(v3_path, "w") as f:
    f.write(v3[:begin_line_end])
    f.write(body + "\n")
    f.write(v3[end_idx:])
PYEOF
