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

# ============================================================
# OpenCode + Ornith isolated lab
# ============================================================

ROOT="$HOME/bench/ornith/opencode-lab"

WORKSPACE="$ROOT/workspace"
CONFIG="$ROOT/config/opencode.json"
CONFIG_DIR="$ROOT/opencode.d"

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

LOGDIR="$ROOT/logs"
RUNS="$ROOT/runs"

IMAGE="lomelidev/llama.cpp:cu130-nccl-sse-faall-10974"
MODEL_DIR="/home/lab/models/ornith15-9b"

PROVIDER="local-ornith"
MODEL_ID="ornith-local"
FULL_MODEL="$PROVIDER/$MODEL_ID"

PORT=8120

# 3 × 256K
NP=3
CTX_SLOT=262144
CTX_TOTAL=786432

OPENCODE_BIN="$(command -v opencode || true)"

mkdir -p \
  "$WORKSPACE" \
  "$(dirname "$CONFIG")" \
  "$CONFIG_DIR" \
  "$XDG_CONFIG" \
  "$XDG_DATA" \
  "$XDG_CACHE" \
  "$LOGDIR" \
  "$RUNS"


# ============================================================
# Environment isolated from your normal OpenCode setup
# ============================================================

export OPENCODE_CONFIG="$CONFIG"
export OPENCODE_CONFIG_DIR="$CONFIG_DIR"

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
    echo "ERROR: $*"
    exit 1
}


# ============================================================
# Workspace
# ============================================================

make_workspace() {

    cat > "$WORKSPACE/go.mod" <<'EOF'
module ornith-lab

go 1.23
EOF

    cat > "$WORKSPACE/worker.go" <<'EOF'
package lab

import (
	"context"
	"sync"
)

type Job struct {
	ID string
}

type Pool struct {
	jobs chan Job
	wg   sync.WaitGroup
}

func NewPool(size int) *Pool {
	return &Pool{
		jobs: make(chan Job, size),
	}
}

func (p *Pool) Start(ctx context.Context, workers int) {
	for i := 0; i < workers; i++ {
		go func() {
			for {
				select {
				case <-ctx.Done():
					return
				case job := <-p.jobs:
					_ = job
				}
			}
		}()
	}
}

func (p *Pool) Submit(job Job) {
	p.jobs <- job
}

func (p *Pool) Close() {
	close(p.jobs)
	p.wg.Wait()
}
EOF

    cat > "$WORKSPACE/dedupe.go" <<'EOF'
package lab

import (
	"sync"
	"time"
)

type Deduper struct {
	mu    sync.Mutex
	items map[string]time.Time
	ttl   time.Duration
}

func NewDeduper(ttl time.Duration) *Deduper {
	return &Deduper{
		items: map[string]time.Time{},
		ttl:   ttl,
	}
}

func (d *Deduper) Seen(id string) bool {
	d.mu.Lock()
	defer d.mu.Unlock()

	now := time.Now()

	if t, ok := d.items[id]; ok && now.Sub(t) < d.ttl {
		return true
	}

	d.items[id] = now
	return false
}
EOF

    cat > "$WORKSPACE/worker_test.go" <<'EOF'
package lab

import (
	"context"
	"testing"
	"time"
)

func TestPoolBasic(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())

	p := NewPool(10)
	p.Start(ctx, 2)

	p.Submit(Job{ID: "a"})

	time.Sleep(10 * time.Millisecond)

	cancel()
	p.Close()
}
EOF

    cat > "$WORKSPACE/README.md" <<'EOF'
# Ornith OpenCode concurrency lab

Small Go project intentionally kept simple for testing:

- OpenCode tool calls
- repo exploration
- multiple concurrent sessions
- subagents
- llama.cpp slot concurrency

Do not treat this as production code.
EOF
}


# ============================================================
# OpenCode config
# ============================================================

make_config() {

    cat > "$CONFIG" <<EOF
{
  "\$schema": "https://opencode.ai/config.json",

  "model": "$FULL_MODEL",

  "providers": {
    "$PROVIDER": {
      "package": "@opencode/ai/providers/openai-compatible",
      "name": "Ornith 1.5 Local / llama.cpp",

      "settings": {
        "baseURL": "http://127.0.0.1:$PORT/v1",
        "apiKey": "local-no-auth"
      },

      "models": {
        "$MODEL_ID": {
          "modelID": "ornith-local",
          "name": "Ornith-1.5-9B Local",

          "capabilities": {
            "tools": true,
            "input": ["text"],
            "output": ["text"]
          },

          "compatibility": {
            "reasoningField": "reasoning_content"
          },

          "limit": {
            "context": 262144,
            "output": 16384
          }
        }
      }
    }
  }
}
EOF

    python3 -m json.tool "$CONFIG" >/dev/null
}


# ============================================================
# llama.cpp
# ============================================================

server_is_correct() {

    curl -fsS "http://127.0.0.1:$PORT/health" \
        >/dev/null 2>&1 || return 1

    docker ps --format '{{.Names}}' \
        | grep -qx ornith || return 1

    docker logs ornith 2>&1 \
        | grep -q "n_slots = 3, n_ctx_slot = 262144" \
        || return 1

    docker inspect ornith \
        --format '{{json .Args}}' 2>/dev/null \
        | grep -q "ornith-local" \
        || return 1

    return 0
}


start_server() {

    if server_is_correct; then
        echo "llama-server ya está correcto: 3 × 256K"
        return
    fi

    echo
    echo "Levantando Ornith:"
    echo "  slots       = 3"
    echo "  ctx/slot    = 262144"
    echo "  ctx total   = 786432"
    echo "  KV          = Q4/Q4"
    echo "  FA          = ON"
    echo "  DFlash      = OFF"
    echo "  vision      = OFF"
    echo

    docker rm -f ornith >/dev/null 2>&1 || true

    docker run -d \
      --name ornith \
      --gpus '"device=0"' \
      --ipc=host \
      -p "$PORT:8080" \
      -v "$MODEL_DIR:/models:ro" \
      -e GGML_CUDA_GRAPH_OPT=1 \
      "$IMAGE" \
      -m /models/Ornith-1.5-9B-Q4_K_L.gguf \
      -a "$MODEL_ID" \
      -ngl 999 \
      -fa on \
      -ctk q4_0 \
      -ctv q4_0 \
      -c "$CTX_TOTAL" \
      -np "$NP" \
      --no-kv-unified \
      --cont-batching \
      --no-mmproj \
      -b 4096 \
      -ub 2048 \
      --cache-ram 32768 \
      --cache-prompt \
      --ctx-checkpoints 4 \
      --jinja \
      --metrics \
      --host 0.0.0.0 \
      --port 8080 \
      --temp 0.6 \
      --top-p 0.95 \
      --top-k 20 \
      --min-p 0 \
      > "$LOGDIR/container-id.txt"


    READY=0

    for i in $(seq 1 120); do

        if curl -fsS \
          "http://127.0.0.1:$PORT/health" \
          >/dev/null 2>&1
        then
            READY=1
            break
        fi

        if ! docker ps --format '{{.Names}}' \
          | grep -qx ornith
        then
            break
        fi

        sleep 1
    done


    docker logs ornith \
        > "$LOGDIR/llama-start.log" 2>&1 || true


    [[ "$READY" == 1 ]] \
        || die "llama-server no arrancó"


    server_is_correct \
        || die "servidor arrancó pero no quedó 3 × 256K"

    echo "llama-server OK"
}


# ============================================================
# Validation
# ============================================================

validate_server() {

    echo
    echo "=== LLAMA HEALTH ==="

    curl -fsS \
      "http://127.0.0.1:$PORT/health"

    echo
    echo


    echo "=== LLAMA MODELS ==="

    curl -fsS \
      "http://127.0.0.1:$PORT/v1/models" \
      | python3 -m json.tool

    echo


    echo "=== LLAMA SLOTS ==="

    docker logs ornith 2>&1 \
      | grep -E \
        'n_slots =|n_ctx_slot =|model loaded' \
      | tail -5

    echo


    echo "=== VRAM ==="

    nvidia-smi \
      --query-gpu=index,memory.used,memory.free \
      --format=csv

    echo
}


validate_opencode() {

    [[ -n "$OPENCODE_BIN" ]] \
        || die "opencode no está instalado/en PATH"

    echo "=== OPENCODE ==="
    "$OPENCODE_BIN" --version

    echo
    echo "=== CONFIG ==="
    echo "$CONFIG"
    python3 -m json.tool "$CONFIG"

    echo
    echo "=== PROVIDER/MODEL SMOKE ==="

    cd "$WORKSPACE"

    OUT="$LOGDIR/provider-smoke.txt"

    timeout 120 \
      "$OPENCODE_BIN" run \
      --standalone \
      --model "$FULL_MODEL" \
      'Respond exactly with: ORNITH_OK' \
      > "$OUT" 2>&1

    if ! grep -q 'ORNITH_OK' "$OUT"; then
        echo
        cat "$OUT"
        die "OpenCode no pudo ejecutar $FULL_MODEL"
    fi

    echo "Provider OK: $FULL_MODEL"
    echo "Smoke OK: ORNITH_OK"
}


# ============================================================
# Smoke test through actual OpenCode
# ============================================================

smoke() {

    echo
    echo "============================================================"
    echo " OpenCode smoke"
    echo "============================================================"
    echo


    cd "$WORKSPACE"


    timeout 180 \
      "$OPENCODE_BIN" run --standalone \
      --auto \
      --model "$FULL_MODEL" \
      --format json \
      "Read README.md and worker.go. Do not modify anything. Tell me in one short paragraph what this project contains." \
      2>&1 \
      | tee "$LOGDIR/smoke.jsonl"


    RC=${PIPESTATUS[0]}

    if [[ "$RC" != 0 ]]; then
        die "OpenCode smoke falló rc=$RC"
    fi


    echo
    echo "Smoke OK"
}


# ============================================================
# TUI
# ============================================================

tui() {

    echo
    echo "============================================================"
    echo " OpenCode isolated TUI"
    echo "============================================================"
    echo
    echo "Workspace : $WORKSPACE"
    echo "Config    : $CONFIG"
    echo "Model     : $FULL_MODEL"
    echo
    echo "Tu OpenCode normal NO se modifica."
    echo


    cd "$WORKSPACE"

    exec "$OPENCODE_BIN" \
      --standalone \
      --auto \
      --model "$FULL_MODEL"
}


# ============================================================
# 6 independent OpenCode sessions
#
# This is useful BEFORE subagent testing:
# we can see real OpenCode tool/LLM duty cycle.
# ============================================================

parallel_test() {

    N="${1:-6}"

    [[ "$N" =~ ^[1-9][0-9]*$ ]] \
      || die "parallel necesita número de agentes"

    echo
    echo "============================================================"
    echo " OpenCode parallel test: $N sesiones"
    echo " llama physical slots: 3"
    echo "============================================================"
    echo


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

    mkdir -p "$PRUN"


    PROMPTS=(
      "Inspect this Go project. Run tools if useful. Do not edit files. Find concurrency or shutdown bugs and report them."
      "Inspect the worker pool implementation. Run tests if useful. Do not edit. Explain three production risks."
      "Review dedupe.go for correctness, memory growth and concurrency. Do not modify files."
      "Run go test and inspect the source. Do not edit anything. Suggest how graceful shutdown should be fixed."
      "Explore this repository and identify race, lifecycle or channel ownership problems. Read-only analysis."
      "Act as a code reviewer. Inspect all Go files and report the most important reliability problems. Do not modify files."
    )


    PIDS=()


    for I in $(seq 1 "$N"); do

        DIR="$PRUN/agent-$I"

        mkdir -p "$DIR"

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


        IDX=$(( (I - 1) % ${#PROMPTS[@]} ))
        PROMPT="${PROMPTS[$IDX]}"


        (
            START=$(date +%s.%N)

            cd "$DIR"

            timeout 300 \
              "$OPENCODE_BIN" run --standalone \
              --auto \
              --model "$FULL_MODEL" \
              --format json \
              "$PROMPT" \
              > "$PRUN/agent-$I.jsonl" \
              2> "$PRUN/agent-$I.err"

            RC=$?

            END=$(date +%s.%N)

            python3 - "$I" "$START" "$END" "$RC" \
              > "$PRUN/agent-$I.timing" <<'PY2'
import sys
i, start, end, rc = sys.argv[1:]
print(f"agent={i} wall={float(end)-float(start):.3f}s rc={rc}")
PY2

        ) &

        PIDS+=("$!")

        echo "agent-$I PID=${PIDS[-1]}"

    done


    echo
    echo "Esperando $N OpenCodes..."

    for PID in "${PIDS[@]}"; do
        wait "$PID" || true
    done


    echo
    echo "============================================================"
    echo " Terminó parallel test"
    echo "============================================================"

    cat "$PRUN"/*.timing | sort -V

    echo
    echo "Outputs:"
    echo "$PRUN"

    echo
    echo "Últimos slots llama:"
    docker logs ornith 2>&1 \
      | grep -E \
        'launch_slot|print_timing|selected slot' \
      | tail -80
}


# ============================================================
# One OpenCode orchestrator asking for actual subagents
# ============================================================

subagent_test() {

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

    mkdir -p "$SRUN"

    cd "$WORKSPACE"

    PROMPT='
Use subagents for this task.

Launch three independent general/explore-style investigations:
1. inspect worker.go for lifecycle/concurrency problems
2. inspect dedupe.go for correctness/memory problems
3. inspect the tests and repository structure

Have them work independently. Do not modify any files.
After they finish, combine their findings into one concise report.
'

    timeout 300 \
      "$OPENCODE_BIN" run --standalone \
      --auto \
      --model "$FULL_MODEL" \
      --format json \
      "$PROMPT" \
      2>&1 \
      | tee "$SRUN/output.jsonl"

    echo
    echo "Subagent output:"
    echo "$SRUN/output.jsonl"
}


# ============================================================
# Status
# ============================================================

status() {

    echo
    echo "ROOT:"
    echo "$ROOT"

    echo
    echo "OPENCODE:"
    echo "$OPENCODE_BIN"
    "$OPENCODE_BIN" --version || true

    echo
    echo "CONFIG:"
    echo "$CONFIG"

    echo
    echo "SERVER:"
    docker ps --filter name=ornith

    echo
    echo "SLOTS:"
    docker logs ornith 2>&1 \
      | grep -E 'n_slots =|n_ctx_slot =' \
      | tail -3 || true

    echo
    echo "GPU:"
    nvidia-smi \
      --query-gpu=index,memory.used,memory.free,utilization.gpu \
      --format=csv
}


# ============================================================
# Setup
# ============================================================

setup() {

    make_workspace
    make_config
    start_server
    validate_server
    validate_opencode

    cat > "$ROOT/env.sh" <<EOF
export OPENCODE_CONFIG="$CONFIG"
export OPENCODE_CONFIG_DIR="$CONFIG_DIR"
export XDG_CONFIG_HOME="$XDG_CONFIG"
export XDG_DATA_HOME="$XDG_DATA"
export XDG_CACHE_HOME="$XDG_CACHE"
export OPENCODE_DISABLE_AUTOUPDATE=1

cd "$WORKSPACE"
EOF

    echo
    echo "============================================================"
    echo " SETUP OK"
    echo "============================================================"
    echo
    echo "Environment helper:"
    echo "  source $ROOT/env.sh"
    echo
}


# ============================================================
# Command router
# ============================================================

CMD="${1:-all}"

case "$CMD" in

    setup)
        setup
        ;;

    smoke)
        setup
        smoke
        ;;

    tui)
        setup
        smoke
        tui
        ;;

    parallel)
        setup
        parallel_test "${2:-6}"
        ;;

    subagents)
        setup
        subagent_test
        ;;

    status)
        status
        ;;

    all)
        setup
        smoke
        tui
        ;;

    *)
        echo "Usage:"
        echo "  $0 setup"
        echo "  $0 smoke"
        echo "  $0 tui"
        echo "  $0 parallel [N]"
        echo "  $0 subagents"
        echo "  $0 status"
        exit 1
        ;;
esac
