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

# ============================================================================
# Ornith P1-F — Prefix-cache oversubscription / eviction
#
# Purpose:
#   Measure what happens when MORE logical conversations than physical llama.cpp
#   slots compete for prefix cache.
#
# Scenarios:
#   F3   = 3 logical sessions on 3 physical slots   (control)
#   F6   = 6 logical sessions on 3 physical slots
#   F12  = 12 logical sessions on 3 physical slots
#
# Each scenario:
#   1) Fresh llama-server
#   2) Prime every logical session once
#   3) Revisit every logical session in the same order
#   4) Measure slot, prompt/cached/processed tokens, reuse %, TTFT, LCP/f_keep
#
# Baseline restored on success OR failure:
#   3 x 256K, Q4/Q4, FA ON, DFlash OFF, vision OFF,
#   cache-prompt ON, hard output 4096.
# ============================================================================

ROOT="${HOME}/bench/ornith"
P1FROOT="${ROOT}/p1f"

IMAGE="lomelidev/llama.cpp:cu130-nccl-sse-faall-10974"
MODEL_DIR="${HOME}/models/ornith15-9b"
MODEL_FILE="Ornith-1.5-9B-Q4_K_L.gguf"

PORT=8120
MODEL_ALIAS="ornith-local"

SLOTS=3
CTX_SLOT=262144
CTX_TOTAL=786432

CACHE_RAM=32768

# Keep outputs tiny: P1-F measures cache/TTFT, not reasoning quality.
TEST_N_PREDICT=48
BASELINE_N_PREDICT=4096

# Two full repetitions per population size.
ROUNDS=2

RUN=""
MON_PID=""
RESTORE_ON_EXIT=0

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

mkdir -p "$P1FROOT"

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

utc_stamp() {
    date -u +%Y%m%dT%H%M%SZ
}

need_cmd() {
    command -v "$1" >/dev/null 2>&1 || die "Falta comando: $1"
}

preflight_tools() {
    local c
    for c in docker curl jq python3 nvidia-smi tmux timeout ss sha256sum awk sed grep column; do
        need_cmd "$c"
    done

    [[ -f "$MODEL_DIR/$MODEL_FILE" ]] || die "No existe modelo: $MODEL_DIR/$MODEL_FILE"
    docker image inspect "$IMAGE" >/dev/null 2>&1 || die "No existe imagen Docker: $IMAGE"
    tmux has-session -t llama 2>/dev/null || die "No existe la sesión tmux 'llama'"
}

# ----------------------------------------------------------------------------
# Cleanup contamination
# ----------------------------------------------------------------------------

clean_old_clients() {
    echo
    echo "== Limpiando clientes que puedan contaminar :8120 =="

    pkill -TERM -f 'opencode run.*local-ornith/ornith-local' 2>/dev/null || true
    pkill -TERM -f 'opencode\.exe serve --stdio --port 0' 2>/dev/null || true
    sleep 1
    pkill -KILL -f 'opencode run.*local-ornith/ornith-local' 2>/dev/null || true
    pkill -KILL -f 'opencode\.exe serve --stdio --port 0' 2>/dev/null || true

    mapfile -t PIDS < <(
        ss -tnp 2>/dev/null \
          | grep ':8120' \
          | grep -oE 'pid=[0-9]+' \
          | cut -d= -f2 \
          | sort -u \
          || true
    )

    if ((${#PIDS[@]})); then
        echo "Cortando clientes conectados a :8120: ${PIDS[*]}"
        kill -TERM "${PIDS[@]}" 2>/dev/null || true
        sleep 1
        local pid
        for pid in "${PIDS[@]}"; do
            kill -KILL "$pid" 2>/dev/null || true
        done
    fi

    if ss -tnp 2>/dev/null | grep -q ':8120'; then
        echo "Conexiones restantes:"
        ss -tnp 2>/dev/null | grep ':8120' || true
    else
        echo "Sin conexiones a :8120"
    fi

    return 0
}

# ----------------------------------------------------------------------------
# llama lifecycle
# ----------------------------------------------------------------------------

start_llama() {
    local n_predict="$1"

    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/${MODEL_FILE}" \
      -a "$MODEL_ALIAS" \
      -ngl 999 \
      -fa on \
      -ctk q4_0 \
      -ctv q4_0 \
      -c "$CTX_TOTAL" \
      -np "$SLOTS" \
      --no-kv-unified \
      --cont-batching \
      --no-mmproj \
      --n-predict "$n_predict" \
      -b 4096 \
      -ub 2048 \
      --cache-ram "$CACHE_RAM" \
      --cache-prompt \
      --ctx-checkpoints 4 \
      --jinja \
      --metrics \
      --host 0.0.0.0 \
      --port 8080 \
      --temp 0.0 \
      --top-p 1.0 \
      --top-k 0 \
      --min-p 0 \
      >/dev/null

    local ok=0
    local _
    for _ in $(seq 1 180); do
        if curl -fsS "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then
            ok=1
            break
        fi

        if ! docker ps --format '{{.Names}}' | grep -qx ornith; then
            break
        fi
        sleep 1
    done

    if [[ "$ok" != "1" ]]; then
        docker logs ornith 2>&1 | tail -120 || true
        die "llama no arrancó"
    fi

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

    grep -Fq 'n_slots = 3, n_ctx_slot = 262144' <<<"$logs" \
      || die "No quedó 3x256K"

    if grep -q 'no FlashAttention vector kernel' <<<"$logs"; then
        die "FA fallback detectado"
    fi

    if grep -Eqi 'cudaMalloc failed|out of memory|capping' <<<"$logs"; then
        die "OOM/capping detectado"
    fi

    return 0
}

restore_baseline() {
    echo
    echo "== Restaurando baseline 3x256K / Q4Q4 / FA / cache-ON / output=4096 =="

    start_llama "$BASELINE_N_PREDICT"

    docker inspect ornith --format '{{json .Args}}' \
      > "${ROOT}/baseline-last-args.json" 2>/dev/null || true

    curl -s "http://127.0.0.1:${PORT}/slots" \
      | jq -r '.[] | "slot=\(.id) ctx=\(.n_ctx) busy=\(.is_processing) max=\(.params.max_tokens)"'

    return 0
}

# ----------------------------------------------------------------------------
# Test corpus and logical sessions
# ----------------------------------------------------------------------------

make_session_files() {
    local max_sessions=12

    mkdir -p "$RUN/sessions"

    python3 - "$RUN/sessions" "$max_sessions" <<'PY'
from pathlib import Path
import hashlib
import random
import sys

root = Path(sys.argv[1])
n = int(sys.argv[2])

for sid in range(1, n + 1):
    random.seed(900000 + sid)

    # Make each logical session distinct from its FIRST line onward,
    # so cross-session prefix reuse is intentionally low.
    lines = [
        f"SESSION-IDENTITY: P1F-SESSION-{sid:02d}",
        "This is a deterministic prefix-cache oversubscription benchmark.",
        "Memorize this session-specific reference table.",
        "Do not use tools.",
        "Reply only with READY.",
        "",
    ]

    for i in range(1, 401):
        seed = f"S{sid:02d}-ROW-{i:04d}-{random.randint(1, 10**9)}"
        checksum = hashlib.sha256(seed.encode()).hexdigest()[:12].upper()
        value = random.randint(100000, 999999)
        lines.append(
            f"S{sid:02d}-REF-{i:04d} value={value} checksum={checksum}"
        )

    prime = "\n".join(lines) + "\n"
    (root / f"session-{sid:02d}-prime.txt").write_text(prime)

    revisit = (
        prime
        + "\n### ASSISTANT\nREADY\n"
        + "\n### USER\n"
        + f"Return ONLY the complete S{sid:02d}-REF-0317 line. No explanation.\n"
    )
    (root / f"session-{sid:02d}-revisit.txt").write_text(revisit)
PY
}

# ----------------------------------------------------------------------------
# Embedded helpers
# ----------------------------------------------------------------------------

write_helpers() {
    cat > "$RUN/request_stream.py" <<'PY'
#!/usr/bin/env python3
import http.client
import json
import sys
import time
from pathlib import Path

req_path = Path(sys.argv[1])
sse_path = Path(sys.argv[2])
meta_path = Path(sys.argv[3])
port = int(sys.argv[4])

body = req_path.read_bytes()

conn = http.client.HTTPConnection("127.0.0.1", port, timeout=600)

t0 = time.monotonic()
epoch0 = time.time()

conn.request(
    "POST",
    "/completion",
    body=body,
    headers={
        "Content-Type": "application/json",
        "Content-Length": str(len(body)),
        "Connection": "close",
    },
)

resp = conn.getresponse()

first_token = None
pieces = []
finish_reason = None
final_obj = None

with sse_path.open("wb") as raw:
    while True:
        line = resp.readline()
        if not line:
            break

        raw.write(line)
        raw.flush()

        stripped = line.strip()

        if not stripped.startswith(b"data:"):
            continue

        payload = stripped[5:].strip()

        if not payload or payload == b"[DONE]":
            continue

        try:
            obj = json.loads(payload)
        except Exception:
            continue

        final_obj = obj

        content = obj.get("content")
        if content:
            if first_token is None:
                first_token = time.monotonic()
            pieces.append(content)

        if obj.get("stop") is True:
            finish_reason = obj.get("stop_type") or obj.get("stop_reason") or "stop"

t1 = time.monotonic()
epoch1 = time.time()

meta = {
    "http_status": resp.status,
    "start_epoch": epoch0,
    "end_epoch": epoch1,
    "ttft_ms": None if first_token is None else (first_token - t0) * 1000.0,
    "total_ms": (t1 - t0) * 1000.0,
    "text": "".join(pieces),
    "finish_reason": finish_reason,
    "final_object": final_obj,
}

meta_path.write_text(json.dumps(meta, indent=2) + "\n")

conn.close()

if resp.status < 200 or resp.status >= 300:
    sys.exit(2)
PY

    cat > "$RUN/poll_slot.py" <<'PY'
#!/usr/bin/env python3
import json
import os
import sys
import time
import urllib.request
from pathlib import Path

pid = int(sys.argv[1])
port = int(sys.argv[2])
jsonl_path = Path(sys.argv[3])
summary_path = Path(sys.argv[4])

summary = {
    "actual_slot": None,
    "task_id": None,
    "prompt_tokens": 0,
    "processed_tokens": 0,
    "cached_tokens": 0,
    "decoded_tokens": 0,
    "max_tokens": None,
}

def alive(p):
    try:
        os.kill(p, 0)
        return True
    except OSError:
        return False

def fetch_slots():
    try:
        with urllib.request.urlopen(
            f"http://127.0.0.1:{port}/slots",
            timeout=0.5,
        ) as r:
            return json.loads(r.read())
    except Exception:
        return []

with jsonl_path.open("w") as out:
    idle_after = 0
    seen_task = None

    while True:
        slots = fetch_slots()
        now = time.time()

        active = [s for s in slots if s.get("is_processing")]

        target = None

        if seen_task is not None:
            for s in active:
                if s.get("id_task") == seen_task:
                    target = s
                    break

        if target is None and active:
            # Requests are sent strictly one-at-a-time in P1-F.
            # Therefore the single newest active task is ours.
            target = max(
                active,
                key=lambda s: int(s.get("id_task") or -1),
            )
            seen_task = target.get("id_task")

        if target is not None:
            rec = {
                "ts": now,
                "id": target.get("id"),
                "id_task": target.get("id_task"),
                "n_ctx": target.get("n_ctx"),
                "prompt": target.get("n_prompt_tokens") or 0,
                "processed": target.get("n_prompt_tokens_processed") or 0,
                "cache": target.get("n_prompt_tokens_cache") or 0,
                "decoded": ((target.get("next_token") or [{}])[0].get("n_decoded") or 0),
                "max_tokens": (target.get("params") or {}).get("max_tokens"),
            }

            out.write(json.dumps(rec) + "\n")
            out.flush()

            summary["actual_slot"] = rec["id"]
            summary["task_id"] = rec["id_task"]
            summary["prompt_tokens"] = max(summary["prompt_tokens"], rec["prompt"])
            summary["processed_tokens"] = max(summary["processed_tokens"], rec["processed"])
            summary["cached_tokens"] = max(summary["cached_tokens"], rec["cache"])
            summary["decoded_tokens"] = max(summary["decoded_tokens"], rec["decoded"])
            summary["max_tokens"] = rec["max_tokens"]
            idle_after = 0
        else:
            if not alive(pid):
                idle_after += 1

        if not alive(pid) and idle_after >= 3:
            break

        time.sleep(0.02)

summary_path.write_text(json.dumps(summary, indent=2) + "\n")
PY

    cat > "$RUN/parse_llama_log.py" <<'PY'
#!/usr/bin/env python3
import json
import re
import sys
from pathlib import Path

path = Path(sys.argv[1])
task = int(sys.argv[2])
slot = int(sys.argv[3])

lines = path.read_text(errors="replace").splitlines()

result = {
    "lcp": None,
    "f_keep": None,
    "prompt_tps": None,
    "gen_tps": None,
    "log_output_tokens": None,
}

launch_idx = None

for i, line in enumerate(lines):
    if re.search(rf"launch_slot_:\s+id\s+{slot}\s+\|\s+task\s+{task}\s+\|", line):
        launch_idx = i
        break

if launch_idx is not None:
    for j in range(launch_idx - 1, -1, -1):
        line = lines[j]

        if "get_availabl" not in line:
            continue

        mslot = re.search(r"get_availabl:\s+id\s+(\d+)", line)
        if mslot and int(mslot.group(1)) != slot:
            continue

        m = re.search(r"f_sim_best\s*=\s*([0-9.]+)", line)
        if m:
            result["lcp"] = float(m.group(1))

        m = re.search(r"f_keep\s*=\s*([0-9.]+)", line)
        if m:
            result["f_keep"] = float(m.group(1))

        break

task_pat = re.compile(rf"\|\s+task\s+{task}\s+\|")

for line in lines:
    if not task_pat.search(line):
        continue

    if "prompt eval time" in line:
        m = re.search(r"([0-9.]+)\s+tokens per second", line)
        if m:
            result["prompt_tps"] = float(m.group(1))

    elif " eval time " in line and "prompt eval time" not in line:
        m = re.search(
            r"/\s*([0-9]+)\s+tokens.*?([0-9.]+)\s+tokens per second",
            line,
        )
        if m:
            result["log_output_tokens"] = int(m.group(1))
            result["gen_tps"] = float(m.group(2))

print(json.dumps(result))
PY

    chmod +x \
      "$RUN/request_stream.py" \
      "$RUN/poll_slot.py" \
      "$RUN/parse_llama_log.py"
}

# ----------------------------------------------------------------------------
# Request building / one request
# ----------------------------------------------------------------------------

build_request() {
    local prompt_file="$1"
    local req_file="$2"

    python3 - "$prompt_file" "$req_file" "$TEST_N_PREDICT" <<'PY'
import json
import sys
from pathlib import Path

prompt_path, req_path, n_predict = sys.argv[1:]

payload = {
    "prompt": Path(prompt_path).read_text(),
    "stream": True,
    "n_predict": int(n_predict),
    "cache_prompt": True,
    "temperature": 0.0,
    "seed": 1,
}

Path(req_path).write_text(json.dumps(payload) + "\n")
PY
}

run_request() {
    local scenario="$1"
    local round="$2"
    local phase="$3"       # prime/revisit
    local session_id="$4"
    local prompt_file="$5"

    local case_dir="$RUN/cases/$scenario/round-$(printf '%02d' "$round")/session-$(printf '%02d' "$session_id")"
    mkdir -p "$case_dir"

    local req_file="$case_dir/${phase}.request.json"
    local sse_file="$case_dir/${phase}.response.sse"
    local meta_file="$case_dir/${phase}.response.json"
    local slot_jsonl="$case_dir/${phase}.slots.jsonl"
    local slot_summary="$case_dir/${phase}.slots-summary.json"
    local llama_log="$case_dir/${phase}.llama.log"
    local parsed_log="$case_dir/${phase}.llama-parsed.json"

    build_request "$prompt_file" "$req_file"

    local log_before
    log_before="$(docker logs ornith 2>&1 | wc -l)"

    python3 "$RUN/request_stream.py" \
      "$req_file" "$sse_file" "$meta_file" "$PORT" &
    local req_pid=$!

    python3 "$RUN/poll_slot.py" \
      "$req_pid" "$PORT" "$slot_jsonl" "$slot_summary" &
    local poll_pid=$!

    local rc=0
    wait "$req_pid" || rc=$?
    wait "$poll_pid" || true

    docker logs ornith 2>&1 \
      | tail -n "+$((log_before + 1))" \
      > "$llama_log"

    if [[ "$rc" != "0" ]]; then
        cat "$meta_file" 2>/dev/null || true
        tail -100 "$llama_log" || true
        die "$scenario round=$round phase=$phase session=$session_id request rc=$rc"
    fi

    local actual_slot task prompt cached processed decoded reuse
    actual_slot="$(jq -r '.actual_slot // -1' "$slot_summary")"
    task="$(jq -r '.task_id // -1' "$slot_summary")"
    prompt="$(jq -r '.prompt_tokens // 0' "$slot_summary")"
    cached="$(jq -r '.cached_tokens // 0' "$slot_summary")"
    processed="$(jq -r '.processed_tokens // 0' "$slot_summary")"
    decoded="$(jq -r '.decoded_tokens // 0' "$slot_summary")"

    [[ "$actual_slot" != "-1" ]] || die "$scenario/$phase/session-$session_id: no detecté slot"
    [[ "$task" != "-1" ]] || die "$scenario/$phase/session-$session_id: no detecté task"

    python3 "$RUN/parse_llama_log.py" "$llama_log" "$task" "$actual_slot" \
      > "$parsed_log"

    reuse="$(awk -v c="$cached" -v p="$prompt" \
      'BEGIN { if (p>0) printf "%.4f", (100*c/p); else print "0.0000" }')"

    python3 - \
      "$scenario" "$round" "$phase" "$session_id" "$actual_slot" "$task" \
      "$slot_summary" "$meta_file" "$parsed_log" "$reuse" \
      "$RUN/results.jsonl" "$RUN/summary.tsv" <<'PY'
import json
import sys

(
    scenario, rnd, phase, sid, actual_slot, task,
    slot_file, meta_file, parsed_file, reuse,
    jsonl_path, tsv_path,
) = sys.argv[1:]

slot = json.load(open(slot_file))
meta = json.load(open(meta_file))
parsed = json.load(open(parsed_file))

row = {
    "scenario": scenario,
    "round": int(rnd),
    "phase": phase,
    "session": int(sid),
    "actual_slot": int(actual_slot),
    "task": int(task),
    "prompt_tokens": slot.get("prompt_tokens", 0),
    "processed_tokens": slot.get("processed_tokens", 0),
    "cached_tokens": slot.get("cached_tokens", 0),
    "reuse_pct": float(reuse),
    "ttft_ms": meta.get("ttft_ms"),
    "total_ms": meta.get("total_ms"),
    "decoded_tokens": slot.get("decoded_tokens", 0),
    "max_tokens": slot.get("max_tokens"),
    "prompt_tps": parsed.get("prompt_tps"),
    "gen_tps": parsed.get("gen_tps"),
    "lcp": parsed.get("lcp"),
    "f_keep": parsed.get("f_keep"),
    "finish_reason": meta.get("finish_reason"),
}

with open(jsonl_path, "a") as f:
    f.write(json.dumps(row) + "\n")

fields = [
    row["scenario"], row["round"], row["phase"], row["session"],
    row["actual_slot"], row["task"],
    row["prompt_tokens"], row["processed_tokens"], row["cached_tokens"],
    f'{row["reuse_pct"]:.2f}',
    "" if row["ttft_ms"] is None else f'{row["ttft_ms"]:.2f}',
    f'{row["total_ms"]:.2f}',
    "" if row["prompt_tps"] is None else f'{row["prompt_tps"]:.2f}',
    "" if row["gen_tps"] is None else f'{row["gen_tps"]:.2f}',
    row["decoded_tokens"],
    "" if row["lcp"] is None else f'{row["lcp"]:.4f}',
    "" if row["f_keep"] is None else f'{row["f_keep"]:.4f}',
]

with open(tsv_path, "a") as f:
    f.write("\t".join(map(str, fields)) + "\n")
PY

    update_progress "$scenario" "$round" "$phase" "$session_id" "$actual_slot"

    printf "  %-4s round=%s %-7s S%02d slot=%s prompt=%s cached=%s reuse=%s%% TTFT=%sms\n" \
      "$scenario" "$round" "$phase" "$session_id" "$actual_slot" "$prompt" "$cached" "$reuse" \
      "$(jq -r '.ttft_ms // 0' "$meta_file")"
}

# ----------------------------------------------------------------------------
# Scenario
# ----------------------------------------------------------------------------

run_scenario() {
    local scenario="$1"
    local count="$2"

    echo
    echo "============================================================================"
    echo "$scenario — ${count} logical sessions / 3 physical slots"
    echo "============================================================================"

    local round sid

    for round in $(seq 1 "$ROUNDS"); do
        echo
        echo "-- round $round/$ROUNDS --"

        start_llama "$TEST_N_PREDICT"

        echo "Priming ${count} sessions..."

        for sid in $(seq 1 "$count"); do
            run_request \
              "$scenario" "$round" prime "$sid" \
              "$RUN/sessions/session-$(printf '%02d' "$sid")-prime.txt"
        done

        echo "Revisiting ${count} sessions..."

        for sid in $(seq 1 "$count"); do
            run_request \
              "$scenario" "$round" revisit "$sid" \
              "$RUN/sessions/session-$(printf '%02d' "$sid")-revisit.txt"
        done
    done
}

# ----------------------------------------------------------------------------
# Monitor / tmux
# ----------------------------------------------------------------------------

start_monitor() {
    (
        echo "timestamp,mem_available_kib,load1,psi_cpu,psi_mem,psi_io,gpu_util,gpu_used_mib,gpu_free_mib,power_w,temp_c"

        while true; do
            local_ts="$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)"
            mem="$(awk '/MemAvailable:/ {print $2}' /proc/meminfo)"
            load1="$(awk '{print $1}' /proc/loadavg)"
            pcpu="$(awk '/some/ {for(i=1;i<=NF;i++) if($i ~ /^avg10=/){split($i,a,"=");print a[2]}}' /proc/pressure/cpu)"
            pmem="$(awk '/some/ {for(i=1;i<=NF;i++) if($i ~ /^avg10=/){split($i,a,"=");print a[2]}}' /proc/pressure/memory)"
            pio="$(awk '/some/ {for(i=1;i<=NF;i++) if($i ~ /^avg10=/){split($i,a,"=");print a[2]}}' /proc/pressure/io)"
            gpu="$(nvidia-smi -i 0 \
              --query-gpu=utilization.gpu,memory.used,memory.free,power.draw,temperature.gpu \
              --format=csv,noheader,nounits)"
            echo "${local_ts},${mem},${load1},${pcpu},${pmem},${pio},${gpu}"
            sleep 1
        done
    ) > "$RUN/system.csv" &

    MON_PID=$!
    echo "$MON_PID" > "$RUN/monitor.pid"
}

stop_monitor() {
    if [[ -n "${MON_PID:-}" ]]; then
        kill "$MON_PID" 2>/dev/null || true
        wait "$MON_PID" 2>/dev/null || true
        MON_PID=""
    fi
}

ensure_window() {
    local name="$1"
    if ! tmux list-windows -t llama -F '#{window_name}' | grep -qx "$name"; then
        tmux new-window -d -t llama -n "$name"
    fi
}

setup_tmux() {
    local w
    for w in Log Check Test Monitor OpenCode; do
        ensure_window "$w"
    done

    tmux send-keys -t llama:Log C-c
    tmux send-keys -t llama:Log \
      'while true; do clear; docker logs -f ornith 2>&1; sleep 1; done' C-m

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

    tmux send-keys -t llama:OpenCode C-c
    tmux send-keys -t llama:OpenCode \
      "watch -n 1 '$SELF slots'" C-m
}

# ----------------------------------------------------------------------------
# Progress / views
# ----------------------------------------------------------------------------

update_progress() {
    local scenario="$1"
    local round="$2"
    local phase="$3"
    local session="$4"
    local slot="$5"

    python3 - "$RUN/progress.json" "$scenario" "$round" "$phase" "$session" "$slot" <<'PY'
import json, os, sys, time

path, scenario, rnd, phase, session, slot = sys.argv[1:]

obj = {
    "scenario": scenario,
    "round": int(rnd),
    "phase": phase,
    "session": int(session),
    "slot": int(slot),
    "updated_epoch": time.time(),
}

tmp = path + ".tmp"
with open(tmp, "w") as f:
    json.dump(obj, f)
os.replace(tmp, path)
PY
}

dashboard() {
    [[ -f "$ROOT/LAST_P1F" ]] || {
        echo "No hay LAST_P1F todavía."
        return
    }

    local d
    d="$(cat "$ROOT/LAST_P1F")"

    clear
    echo "ORNITH P1-F — OVERSUBSCRIPTION / CACHE EVICTION"
    echo "============================================================================"
    echo "$d"
    echo

    if [[ -f "$d/progress.json" ]]; then
        jq -r '
          "Current : \(.scenario)
Round   : \(.round)
Phase   : \(.phase)
Session : \(.session)
Slot    : \(.slot)"
        ' "$d/progress.json"
    else
        echo "Esperando primer sample..."
    fi

    echo
    echo "ÚLTIMOS RESULTADOS"
    echo "============================================================================"
    if [[ -s "$d/summary.tsv" ]]; then
        tail -n 15 "$d/summary.tsv" | column -t -s $'\t'
    fi

    echo
    echo "GPU0"
    echo "============================================================================"
    nvidia-smi -i 0 \
      --query-gpu=utilization.gpu,memory.used,memory.free,power.draw,temperature.gpu \
      --format=csv,noheader
}

slots_view() {
    curl -s "http://127.0.0.1:${PORT}/slots" \
      | jq -r '
        .[] |
        "SLOT \(.id) task=\(.id_task) busy=\(.is_processing)
ctx=\(.n_ctx)
prompt=\(.n_prompt_tokens)
processed=\(.n_prompt_tokens_processed)
cache=\(.n_prompt_tokens_cache)
decoded=\(.next_token[0].n_decoded // 0)
max_tokens=\(.params.max_tokens)
---------------------------------------------"
      '
}

# ----------------------------------------------------------------------------
# Report
# ----------------------------------------------------------------------------

make_report() {
    python3 - "$RUN" <<'PY'
from pathlib import Path
import json
import statistics
import sys

run = Path(sys.argv[1])

rows = [
    json.loads(x)
    for x in (run / "results.jsonl").read_text().splitlines()
    if x.strip()
]

def med(xs):
    xs = [float(x) for x in xs if isinstance(x, (int, float))]
    return statistics.median(xs) if xs else None

def pct(xs, q):
    xs = sorted(float(x) for x in xs if isinstance(x, (int, float)))
    if not xs:
        return None
    if len(xs) == 1:
        return xs[0]
    pos = (len(xs) - 1) * q
    lo = int(pos)
    hi = min(lo + 1, len(xs) - 1)
    frac = pos - lo
    return xs[lo] * (1 - frac) + xs[hi] * frac

scenarios = sorted({r["scenario"] for r in rows})
summary = {}

for s in scenarios:
    prime = [r for r in rows if r["scenario"] == s and r["phase"] == "prime"]
    revisit = [r for r in rows if r["scenario"] == s and r["phase"] == "revisit"]

    def vals(rs, key):
        return [r.get(key) for r in rs if isinstance(r.get(key), (int, float))]

    hot = [r for r in revisit if float(r.get("reuse_pct") or 0) >= 90.0]
    partial = [
        r for r in revisit
        if 10.0 <= float(r.get("reuse_pct") or 0) < 90.0
    ]
    cold = [r for r in revisit if float(r.get("reuse_pct") or 0) < 10.0]

    summary[s] = {
        "prime_samples": len(prime),
        "revisit_samples": len(revisit),

        "hot_revisits": len(hot),
        "partial_revisits": len(partial),
        "cold_revisits": len(cold),

        "hot_rate_pct": 100.0 * len(hot) / len(revisit) if revisit else None,
        "partial_rate_pct": 100.0 * len(partial) / len(revisit) if revisit else None,
        "cold_rate_pct": 100.0 * len(cold) / len(revisit) if revisit else None,

        "revisit_median_reuse_pct": med(vals(revisit, "reuse_pct")),
        "revisit_median_ttft_ms": med(vals(revisit, "ttft_ms")),
        "revisit_p10_ttft_ms": pct(vals(revisit, "ttft_ms"), 0.10),
        "revisit_p90_ttft_ms": pct(vals(revisit, "ttft_ms"), 0.90),

        "hot_median_ttft_ms": med(vals(hot, "ttft_ms")),
        "cold_median_ttft_ms": med(vals(cold, "ttft_ms")),

        "revisit_median_processed_tokens": med(vals(revisit, "processed_tokens")),
        "revisit_median_cached_tokens": med(vals(revisit, "cached_tokens")),
    }

(run / "summary.json").write_text(
    json.dumps(summary, indent=2) + "\n"
)

def f(v, n=2):
    return "-" if v is None else f"{v:.{n}f}"

md = [
    "# Ornith P1-F — Prefix Cache Oversubscription / Eviction",
    "",
    f"Run: `{run}`",
    "",
    "| Scenario | logical sessions | revisit n | hot >=90% | partial | cold <10% | hot rate | reuse med | TTFT med ms | hot TTFT med | cold TTFT med |",
    "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|",
]

for s in scenarios:
    x = summary[s]
    logical = int(s.replace("F", "")) if s.startswith("F") else 0

    md.append(
        f"| {s} | {logical} | {x['revisit_samples']} "
        f"| {x['hot_revisits']} | {x['partial_revisits']} | {x['cold_revisits']} "
        f"| {f(x['hot_rate_pct'])}% | {f(x['revisit_median_reuse_pct'])}% "
        f"| {f(x['revisit_median_ttft_ms'])} "
        f"| {f(x['hot_median_ttft_ms'])} | {f(x['cold_median_ttft_ms'])} |"
    )

md += [
    "",
    "## Interpretation guide",
    "",
    "- `hot >=90%`: the logical session returned with nearly all of its prefix reusable.",
    "- `partial`: some prefix survived, but not most of it.",
    "- `cold <10%`: the session effectively paid a fresh prefill.",
    "",
    "## Baseline restored after P1-F",
    "",
    "- 3 × 256K",
    "- KV Q4/Q4",
    "- FlashAttention ON",
    "- DFlash OFF",
    "- vision OFF",
    "- cache-prompt ON",
    "- hard output 4096",
    "",
]

report = "\n".join(md) + "\n"
(run / "report.md").write_text(report)
print(report)
PY
}

# ----------------------------------------------------------------------------
# Manifest
# ----------------------------------------------------------------------------

make_manifest() {
    local image_id model_sha
    image_id="$(docker image inspect "$IMAGE" --format '{{.Id}}')"
    model_sha="$(sha256sum "$MODEL_DIR/$MODEL_FILE" | awk '{print $1}')"

    cat > "$RUN/manifest.json" <<EOF
{
  "created_utc": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "suite": "Ornith P1-F prefix-cache oversubscription",
  "image": "$IMAGE",
  "image_id": "$image_id",
  "model_file": "$MODEL_FILE",
  "model_sha256": "$model_sha",
  "physical_slots": $SLOTS,
  "ctx_per_slot": $CTX_SLOT,
  "ctx_total": $CTX_TOTAL,
  "kv_k": "q4_0",
  "kv_v": "q4_0",
  "flash_attention": true,
  "dflash": false,
  "vision": false,
  "cache_ram_mb": $CACHE_RAM,
  "test_n_predict": $TEST_N_PREDICT,
  "rounds": $ROUNDS,
  "logical_session_populations": [3, 6, 12]
}
EOF
}

# ----------------------------------------------------------------------------
# Trap
# ----------------------------------------------------------------------------

cleanup_runtime() {
    stop_monitor || true
}

on_exit() {
    local rc=$?
    trap - EXIT INT TERM

    cleanup_runtime || true

    if [[ "$RESTORE_ON_EXIT" == "1" ]]; then
        restore_baseline || true
    fi

    exit "$rc"
}

# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------

run_all() {
    preflight_tools
    clean_old_clients

    RUN="$P1FROOT/p1f-$(utc_stamp)"
    mkdir -p "$RUN"/{cases,sessions}

    echo "$RUN" > "$ROOT/LAST_P1F"

    printf \
"scenario\tround\tphase\tsession\tactual_slot\ttask\tprompt\tprocessed\tcached\treuse_pct\tttft_ms\ttotal_ms\tprompt_tps\tgen_tps\tdecoded\tlcp\tf_keep\n" \
      > "$RUN/summary.tsv"

    : > "$RUN/results.jsonl"

    make_manifest
    make_session_files
    write_helpers
    setup_tmux
    start_monitor

    RESTORE_ON_EXIT=1
    trap on_exit EXIT INT TERM

    update_progress "F3" 0 "setup" 0 -1

    run_scenario "F3" 3
    run_scenario "F6" 6
    run_scenario "F12" 12

    update_progress "ANALYSIS" "$ROUNDS" "done" 0 -1

    make_report | tee "$RUN/report-console.txt"

    docker logs ornith > "$RUN/llama-last.log" 2>&1 || true

    RESTORE_ON_EXIT=0
    cleanup_runtime
    restore_baseline

    echo
    echo "============================================================================"
    echo "P1-F TERMINADA — BASELINE RESTAURADO"
    echo "============================================================================"
    echo "Run:      $RUN"
    echo "TSV:      $RUN/summary.tsv"
    echo "JSON:     $RUN/summary.json"
    echo "Reporte:  $RUN/report.md"
}

results_view() {
    [[ -f "$ROOT/LAST_P1F" ]] || die "No existe $ROOT/LAST_P1F"

    local d
    d="$(cat "$ROOT/LAST_P1F")"

    echo "$d"
    echo

    if [[ -f "$d/report.md" ]]; then
        cat "$d/report.md"
    else
        echo "P1-F aún no termina."
        echo
        tail -n 25 "$d/summary.tsv" | column -t -s $'\t'
    fi
}

case "${1:-run}" in
    run)
        run_all
        ;;
    dashboard)
        dashboard
        ;;
    slots)
        slots_view
        ;;
    watch)
        watch -n 1 "$SELF slots"
        ;;
    results)
        results_view
        ;;
    restore)
        restore_baseline
        ;;
    *)
        echo "Uso:"
        echo "  $SELF run"
        echo "  $SELF dashboard"
        echo "  $SELF slots"
        echo "  $SELF watch"
        echo "  $SELF results"
        echo "  $SELF restore"
        exit 1
        ;;
esac
