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

ROOT="$HOME/bench/ornith/opencode-lab"
BASE="$ROOT/workspace"
RUNS="$ROOT/runs"

XDG_CONFIG="$ROOT/xdg-config"
XDG_DATA="$ROOT/xdg-data"
XDG_CACHE="$ROOT/xdg-cache"

MODEL="local-ornith/ornith-local"

SELF="$(readlink -f "$0")"

mkdir -p "$RUNS"

export XDG_CONFIG_HOME="$XDG_CONFIG"
export XDG_DATA_HOME="$XDG_DATA"
export XDG_CACHE_HOME="$XDG_CACHE"
export OPENCODE_DISABLE_AUTOUPDATE=1


die() {
    echo "ERROR: $*" >&2
    exit 1
}


# ============================================================
# STATUS
# ============================================================

status() {

    LAST="$RUNS/LAST_TMUX_RUN"

    if [[ ! -f "$LAST" ]]; then
        echo "No hay run activo."
        exit 0
    fi

    RUN="$(cat "$LAST")"

    clear

    echo "OPENCode → Ornith"
    echo "=============================================================="
    echo "Run: $RUN"
    echo
    echo "3 slots físicos × 256K"
    echo

    for i in 1 2 3 4 5 6; do

        F="$RUN/status/agent-$i.status"

        if [[ -f "$F" ]]; then
            cat "$F"
        else
            printf "A%-2s %-10s\n" "$i" "WAIT"
        fi

    done

    echo
    echo "--------------------------------------------------------------"

    DONE=$(grep -h ' DONE ' "$RUN"/status/*.status 2>/dev/null | wc -l || true)
    FAIL=$(grep -h ' FAIL ' "$RUN"/status/*.status 2>/dev/null | wc -l || true)

    echo "DONE=$DONE/6   FAIL=$FAIL"
    echo

    if docker ps --format '{{.Names}}' | grep -qx ornith; then

        echo "GPU:"
        nvidia-smi \
          --query-gpu=index,memory.used,memory.free,utilization.gpu,power.draw \
          --format=csv,noheader \
          -i 0

    fi
}


# ============================================================
# RESULTS
# ============================================================

results() {

    LAST="$RUNS/LAST_TMUX_RUN"

    [[ -f "$LAST" ]] || die "No existe LAST_TMUX_RUN"

    RUN="$(cat "$LAST")"

    echo
    echo "RUN:"
    echo "$RUN"
    echo

    echo "TIMINGS"
    echo "=============================================================="

    for i in 1 2 3 4 5 6; do

        F="$RUN/timing/agent-$i.txt"

        if [[ -f "$F" ]]; then
            cat "$F"
        else
            echo "agent=$i sin timing"
        fi

    done

    echo
    echo "OUTPUT SIZES"
    echo "=============================================================="

    for i in 1 2 3 4 5 6; do

        F="$RUN/logs/agent-$i.log"

        if [[ -f "$F" ]]; then
            printf "agent=%s  " "$i"
            du -h "$F" | awk '{print $1}'
        fi

    done
}


# ============================================================
# ONE AGENT
# ============================================================

agent() {

    RUN="$2"
    I="$3"
    PANE="$4"

    DIR="$RUN/workspaces/agent-$I"
    PROMPT_FILE="$RUN/prompts/agent-$I.txt"
    LOG="$RUN/logs/agent-$I.log"
    STATUS="$RUN/status/agent-$I.status"
    TIMING="$RUN/timing/agent-$I.txt"

    export XDG_CONFIG_HOME="$XDG_CONFIG"
    export XDG_DATA_HOME="$XDG_DATA"
    export XDG_CACHE_HOME="$XDG_CACHE"
    export OPENCODE_DISABLE_AUTOUPDATE=1

    cd "$DIR"

    START_NS=$(date +%s%N)
    START_HUMAN=$(date '+%H:%M:%S')

    printf "A%s  RUNNING    start=%s\n" \
        "$I" "$START_HUMAN" > "$STATUS"

    tmux select-pane -t "$PANE" -T "A$I RUN"

    clear

    echo "============================================================"
    echo " AGENT $I"
    echo "============================================================"
    echo
    echo "Workspace:"
    echo "$DIR"
    echo
    echo "Model:"
    echo "$MODEL"
    echo
    echo "Prompt:"
    cat "$PROMPT_FILE"
    echo
    echo "============================================================"
    echo

    set +e

    timeout 420 \
      opencode run \
      --auto \
      --model "$MODEL" \
      "$(cat "$PROMPT_FILE")" \
      2>&1 | tee "$LOG"

    RC=${PIPESTATUS[0]}

    set -e

    END_NS=$(date +%s%N)

    WALL=$(python3 - "$START_NS" "$END_NS" <<'PY2'
import sys
a, b = map(int, sys.argv[1:])
print(f"{(b-a)/1e9:.3f}")
PY2
)

    END_HUMAN=$(date '+%H:%M:%S')

    if [[ "$RC" == "0" ]]; then

        STATE="DONE"

        printf "A%s  DONE       wall=%ss  end=%s\n" \
          "$I" "$WALL" "$END_HUMAN" > "$STATUS"

        tmux select-pane -t "$PANE" -T "A$I DONE"

    else

        STATE="FAIL"

        printf "A%s  FAIL       rc=%s wall=%ss\n" \
          "$I" "$RC" "$WALL" > "$STATUS"

        tmux select-pane -t "$PANE" -T "A$I FAIL"

    fi

    printf "agent=%s state=%s rc=%s wall=%ss start=%s end=%s\n" \
      "$I" "$STATE" "$RC" "$WALL" "$START_HUMAN" "$END_HUMAN" \
      > "$TIMING"

    echo
    echo
    echo "============================================================"
    echo " AGENT $I $STATE"
    echo " rc=$RC"
    echo " wall=${WALL}s"
    echo "============================================================"
    echo

    exec bash
}


# ============================================================
# PREPARE ONE AGENT COPY
# ============================================================

prepare_agent() {

    RUN="$1"
    I="$2"

    DIR="$RUN/workspaces/agent-$I"

    mkdir -p "$DIR"

    cp -a "$BASE/." "$DIR/"


    # Para este stress test no queremos 16K de output runaway.
    python3 - "$DIR/opencode.json" <<'PY2'
import json
import sys

p = sys.argv[1]

with open(p) as f:
    d = json.load(f)

m = d["providers"]["local-ornith"]["models"]["ornith-local"]

m.setdefault("limit", {})
m["limit"]["context"] = 262144
m["limit"]["output"] = 8192

with open(p, "w") as f:
    json.dump(d, f, indent=2)
    f.write("\n")
PY2
}


# ============================================================
# START
# ============================================================

start() {

    N="${2:-6}"

    [[ "$N" == "6" ]] || die "Esta vista está diseñada para 6 agentes"

    echo
    echo "Verificando llama..."

    curl -fsS http://127.0.0.1:8120/health >/dev/null \
      || die "llama :8120 no responde"

    if ! docker inspect ornith >/dev/null 2>&1; then
        die "container ornith no está corriendo"
    fi

    LLAMA_LOGS="$(docker logs ornith 2>&1)"

    if ! grep -Fq "n_slots = 3, n_ctx_slot = 262144" <<< "$LLAMA_LOGS"; then
        echo
        echo "Configuración encontrada:"
        grep -F "n_slots =" <<< "$LLAMA_LOGS" | tail -5 || true
        echo
        die "ornith no está configurado como 3 × 256K"
    fi


    # No queremos mezclar este test con un parallel anterior.
    OLD=$(
      pgrep -af \
        'opencode run.*local-ornith/ornith-local' \
        || true
    )

    if [[ -n "$OLD" ]]; then

        echo
        echo "Todavía existen OpenCode runs anteriores:"
        echo
        echo "$OLD"
        echo
        echo "Espera a que terminen o cancélalos antes de arrancar."
        exit 2

    fi


    RUN="$RUNS/tmux-$(date -u +%Y%m%dT%H%M%SZ)"

    mkdir -p \
      "$RUN"/{workspaces,prompts,logs,status,timing}

    echo "$RUN" > "$RUNS/LAST_TMUX_RUN"


    # ========================================================
    # Prompts: trabajo realista y acotado
    # ========================================================

    cat > "$RUN/prompts/agent-1.txt" <<'EOF'
Inspect worker.go and worker_test.go.
Fix the worker pool lifecycle and graceful shutdown correctly.
Use tools, edit files, and run tests.
Keep the solution focused and stop once tests pass.
At the end give a short summary.
EOF


    cat > "$RUN/prompts/agent-2.txt" <<'EOF'
Inspect dedupe.go.
Find concurrency, expiration, and unbounded-memory problems.
Implement a production-quality fix and add focused tests.
Run the tests.
Keep the final explanation concise.
EOF


    cat > "$RUN/prompts/agent-3.txt" <<'EOF'
Review the complete Go project for goroutine leaks, channel ownership,
shutdown races, and unsafe lifecycle behavior.
Use tools and run go test.
Fix concrete problems you find.
Do not over-engineer.
EOF


    cat > "$RUN/prompts/agent-4.txt" <<'EOF'
Run the Go tests and inspect the implementation as a reliability engineer.
Improve graceful cancellation and shutdown behavior where needed.
Add or improve tests proving the fixes.
Stop once the relevant tests pass.
EOF


    cat > "$RUN/prompts/agent-5.txt" <<'EOF'
Inspect this Go repository for backpressure and bounded-concurrency problems.
Implement one focused improvement that makes the worker system safer in production.
Run tests and give a brief summary.
EOF


    cat > "$RUN/prompts/agent-6.txt" <<'EOF'
Act as a senior Go code reviewer.
Inspect all source and test files and run tests if useful.
Do not modify files.
Report the five most important correctness or concurrency observations.
Be concise.
EOF


    for i in 1 2 3 4 5 6; do

        prepare_agent "$RUN" "$i"

        printf "A%s  WAIT\n" "$i" \
          > "$RUN/status/agent-$i.status"

    done


    # ========================================================
    # Preflight using SHARED OpenCode service.
    # NO --standalone.
    # ========================================================

    echo
    echo "Probando provider mediante servicio compartido..."

    cd "$RUN/workspaces/agent-6"

    PREFLIGHT="$RUN/logs/preflight.log"

    timeout 60 \
      opencode run \
      --model "$MODEL" \
      'Respond exactly with: SHARED_OK' \
      > "$PREFLIGHT" 2>&1 \
      || {
        cat "$PREFLIGHT"
        die "preflight OpenCode falló"
      }

    grep -q 'SHARED_OK' "$PREFLIGHT" \
      || {
        cat "$PREFLIGHT"
        die "provider no devolvió SHARED_OK"
      }

    echo "Shared OpenCode service OK"


    # ========================================================
    # Recreate OpenCode tmux window with 6 panes
    # ========================================================

    tmux kill-window -t llama:OpenCode 2>/dev/null || true

    tmux new-window -d -t llama -n OpenCode


    P0=$(
      tmux list-panes \
        -t llama:OpenCode \
        -F '#{pane_id}' \
        | head -1
    )

    P1=$(
      tmux split-window \
        -h \
        -P \
        -F '#{pane_id}' \
        -t "$P0"
    )

    P2=$(
      tmux split-window \
        -h \
        -P \
        -F '#{pane_id}' \
        -t "$P1"
    )

    tmux select-layout \
      -t llama:OpenCode \
      even-horizontal


    mapfile -t COLS < <(
      tmux list-panes \
        -t llama:OpenCode \
        -F '#{pane_id}'
    )


    for P in "${COLS[@]}"; do
        tmux split-window -v -t "$P"
    done


    tmux select-layout \
      -t llama:OpenCode \
      tiled

    tmux set-option \
      -t llama:OpenCode \
      pane-border-status top


    mapfile -t PANES < <(
      tmux list-panes \
        -t llama:OpenCode \
        -F '#{pane_id}'
    )


    if [[ "${#PANES[@]}" != "6" ]]; then
        die "esperaba 6 panes y obtuve ${#PANES[@]}"
    fi


    # ========================================================
    # Check tab = live status
    # ========================================================

    tmux send-keys \
      -t llama:Check \
      C-c

    tmux send-keys \
      -t llama:Check \
      "watch -n 1 '$SELF status'" \
      C-m


    # ========================================================
    # Launch ALL 6 nearly simultaneously
    # ========================================================

    echo
    echo "Lanzando 6 agentes..."
    echo
    echo "Run:"
    echo "$RUN"
    echo


    for i in 1 2 3 4 5 6; do

        IDX=$((i - 1))
        P="${PANES[$IDX]}"

        tmux select-pane \
          -t "$P" \
          -T "A$i WAIT"

        CMD="$SELF agent '$RUN' '$i' '$P'"

        tmux send-keys \
          -t "$P" \
          "$CMD" \
          C-m

    done


    echo
    echo "============================================================"
    echo " 6 AGENTES LANZADOS"
    echo "============================================================"
    echo
    echo "OpenCode window : 6 panes live"
    echo "Check window    : status"
    echo "Log window      : llama slots"
    echo "Monitor window  : GPU/CPU/RAM"
    echo
    echo "Results:"
    echo "  $SELF results"
    echo

    tmux select-window -t llama:OpenCode
}


# ============================================================
# ROUTER
# ============================================================

CMD="${1:-start}"

case "$CMD" in

    start)
        start "$@"
        ;;

    agent)
        agent "$@"
        ;;

    status)
        status
        ;;

    results)
        results
        ;;

    *)
        echo "Usage:"
        echo "  $SELF start 6"
        echo "  $SELF status"
        echo "  $SELF results"
        exit 1
        ;;
esac
