#!/bin/sh
# One quiet, guided run of the Axol contributor-payment starter: one line per step,
# the details in .start/*.log, the exact fix when a step fails, and report.json.
# The other scripts still run on their own; this only sequences them.
# Usage: sh start.sh [all|payouts|reads|image|mcp-config]   (default: all)
set -eu

revision=74c5796f33b449310e841d6325c647f6d7a83952
project=$(cd "$(dirname "$0")" && pwd -P)
caller=$(pwd -P)
repo="$project/raxol-agent"
package="$repo/packages/raxol_payments"
logs="$project/.start"
evidence="$logs/evidence"
# Unique per invocation, even for two runs in the same second.
run_id="$(date -u +%Y-%m-%dT%H:%M:%SZ)-$$"
steps=6
current=""

step() {
  current=$2
  printf '[%s/%s] %-10s ' "$1" "$steps" "$2"
}

ok() {
  printf 'ok    %s\n' "$1"
}

skipped() {
  printf 'skip  %s\n' "$1"
}

# Print the failing step's own one-line reason and fix, or the end of its log.
fail() {
  log=$1
  printf 'FAILED\n'
  if grep -Eq '^(setup|fix|check-[a-z]+): ' "$log"; then
    grep -E '^(setup|fix|check-[a-z]+): ' "$log" | sed 's/^/      /'
  else
    tail -n 3 "$log" | sed 's/^/      /'
  fi
  printf '      details: %s\n' "${log#"$project"/}"
  if [ "$caller" != "$project" ]; then
    printf '      run the fix from: %s\n' "$project"
  fi
  # report.json always describes this invocation, failed or not.
  write_report "$current" "${log#"$project"/}" ||
    printf '      report.json: could not be rewritten for this failed run\n'
  exit 1
}

# Evidence: a step that succeeds writes .start/evidence/<step> with this run's id
# and its time; a step that starts deletes its old file first, so a failure never
# leaves earlier evidence behind. report.json lists in "ran" only steps with a
# file, and says whether each one ran in this invocation.
forget() {
  for key in "$@"; do
    rm -f "$evidence/$key"
  done
}

prove() {
  mkdir -p "$evidence"
  printf 'run=%s\nat=%s\n' "$run_id" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$evidence/$1"
}

# A step that has run but cannot name its result has failed: never print an
# ok line with an empty value.
require_value() {
  if [ -z "$2" ]; then
    printf 'check-result: %s\nfix: see the rest of this log, then rerun sh start.sh\n' "$3" >>"$1"
    fail "$1"
  fi
}

locked_raxol() {
  [ -f "$package/mix.lock" ] || return 0
  sed -n 's/.*"raxol": {:hex, :raxol, "\([0-9.]*\)".*/\1/p' "$package/mix.lock"
}

# The fixture's evidence: 35 USDC refused before any receipt, 25 USDC allowed.
both_decisions() {
  grep -q '^35 USDC: refused' "$1" && grep -q '^25 USDC: allowed' "$1"
}

recorded() {
  [ -f "$logs/toolchain" ] || return 0
  sed -n "s/^$1=//p" "$logs/toolchain"
}

fetch_source() {
  step 1 source
  forget source
  sh "$project/setup.sh" source >"$logs/source.log" 2>&1 || fail "$logs/source.log"
  ok "raxol-agent $(printf '%s' "$revision" | cut -c1-7) (pinned)"
  prove source
}

check_toolchain() {
  step 2 toolchain
  forget toolchain
  sh "$project/setup.sh" toolchain >"$logs/toolchain.log" 2>&1 || fail "$logs/toolchain.log"
  require_value "$logs/toolchain.log" "$(recorded elixir)" "no Elixir version was recorded"
  require_value "$logs/toolchain.log" "$(recorded otp)" "no OTP release was recorded"
  ok "Elixir $(recorded elixir) on Erlang/OTP $(recorded otp)"
  prove toolchain
}

build() {
  step 3 build
  forget build
  started=$(date +%s)
  sh "$project/setup.sh" build >"$logs/build.log" 2>&1 || fail "$logs/build.log"
  require_value "$logs/build.log" "$(locked_raxol)" "no Raxol version in raxol-agent's mix.lock"
  ok "Raxol $(locked_raxol), lockfile unchanged ($(($(date +%s) - started))s)"
  prove build
}

run_fixture() {
  step 4 fixture
  forget fixture
  sh "$project/setup.sh" fixture >"$logs/fixture.log" 2>&1 || fail "$logs/fixture.log"
  both_decisions "$logs/fixture.log" || fail "$logs/fixture.log"
  ok "35 USDC refused, 25 USDC allowed (mock receipt)"
  prove fixture
}

# The first result worth showing: an editable payout round through a real Ledger.
run_payouts() {
  step "$1" payouts
  forget payouts
  if [ ! -f "$logs/toolchain" ]; then
    printf '%s\n' "check-build: no build found" "fix: run sh start.sh first" >"$logs/payouts.log"
    fail "$logs/payouts.log"
  fi
  use_toolchain 2>"$logs/payouts.log" || fail "$logs/payouts.log"
  if ! screen=$(cd "$package" && MIX_ENV=dev "$elixir_bin/mix" run --no-start --no-compile "$project/payout-panel.exs" 2>"$logs/payouts.err"); then
    cp "$logs/payouts.err" "$logs/payouts.log"
    fail "$logs/payouts.log"
  fi
  printf '%s\n' "$screen" >"$logs/payouts.log"
  require_value "$logs/payouts.log" "$(printf '%s\n' "$screen" | sed -n 's/^payout round: //p')" "the payout round printed no summary"
  ok "$(printf '%s\n' "$screen" | sed -n 's/^payout round: //p')"
  prove payouts
  printf '%s\n' "$screen" | sed '/^payout round: /d'
}

# Explain a rejected toolchain record in the form fail() prints.
reject_toolchain() {
  printf 'check-toolchain: %s\nfix: sh setup.sh toolchain, then rerun\n' "$1" >&2
  return 1
}

# mix as setup.sh resolved it inside raxol-agent, with the same Mix home, and only
# if the record still holds: one absolute entry per folder, mix, elixir and erl
# executable there, and still Elixir 1.20.x on OTP 29. Sets elixir_bin, which
# callers use to run mix by absolute path; PATH never gains an empty entry.
use_toolchain() {
  [ -f "$logs/toolchain" ] || reject_toolchain "no recorded toolchain" || return 1
  for key in path elixir_bin erlang_bin; do
    [ "$(grep -c "^$key=" "$logs/toolchain")" -eq 1 ] ||
      reject_toolchain "the recorded toolchain has no single $key entry" || return 1
  done
  elixir_bin=$(recorded elixir_bin)
  erlang_bin=$(recorded erlang_bin)
  [ "$(recorded path)" = "$elixir_bin:$erlang_bin" ] ||
    reject_toolchain "the recorded toolchain path does not match its folders" || return 1
  for folder in "$elixir_bin" "$erlang_bin"; do
    case "$folder" in
      /*) [ -d "$folder" ] || reject_toolchain "the recorded folder $folder is gone" || return 1 ;;
      *) reject_toolchain "the recorded folder '$folder' is not absolute" || return 1 ;;
    esac
  done
  for tool in "$elixir_bin/mix" "$elixir_bin/elixir" "$erlang_bin/erl"; do
    [ -f "$tool" ] && [ -x "$tool" ] || reject_toolchain "no executable $tool" || return 1
  done
  for name in MIX_HOME MIX_ARCHIVES; do
    value=$(recorded "$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')")
    if [ -n "$value" ]; then
      export "$name=$value"
    else
      unset "$name"
    fi
  done
  inherited=$(printf '%s' "$PATH" | tr ':' '\n' | grep -v -e '^$' -e '^\.$' | paste -sd ':' -)
  PATH="$elixir_bin:$erlang_bin${inherited:+:$inherited}"
  export PATH
  # shellcheck disable=SC2016
  found=$("$elixir_bin/elixir" --eval 'IO.puts("#{System.version()} #{:erlang.system_info(:otp_release)}")' 2>/dev/null) ||
    reject_toolchain "the recorded toolchain no longer starts" || return 1
  case "$found" in
    "1.20."*" 29") ;;
    *) reject_toolchain "the recorded toolchain is now Elixir/OTP '$found'; need 1.20.x on OTP 29" || return 1 ;;
  esac
}

live_reads() {
  step "$1" reads
  forget chain-reads xochi-preview
  rm -f "$logs/mcp.json" "$logs/xochi.json"
  tools=""
  blocks=""
  if python3 "$project/check-mcp.py" --json "$logs/mcp.json" >"$logs/mcp.log" 2>&1; then
    tools=$(sed -n 's/^Web3 tools (\([0-9]*\)).*/\1/p' "$logs/mcp.log")
    # One outcome per chain, in order: "Ethereum block N" or "Base skipped (why)".
    blocks=$(sed -n 's/^\([A-Za-z]*\) (eip155:[0-9]*): block \([0-9]*\).*/\1 block \2/p' "$logs/mcp.log")
    chains=$(sed -n -e 's/^\([A-Za-z]*\) (eip155:[0-9]*): block \([0-9]*\).*/\1 block \2/p' \
      -e 's/^\([A-Za-z]*\) (eip155:[0-9]*): skipped (\(.*\)), not a read$/\1 skipped (\2)/p' "$logs/mcp.log")
    if printf '%s\n' "$chains" | grep -q ' skipped '; then
      chains=$(printf '%s\n' "$chains" | paste -sd ';' - | sed 's/;/; /g')
    else
      chains=$(printf '%s\n' "$chains" | paste -sd ',' - | sed 's/,/, /g')
    fi
  fi
  if [ -n "${blocks:-}" ] && [ -n "${tools:-}" ]; then
    ok "$chains"
    prove chain-reads
  else
    skipped "public chain read unavailable; retry with sh start.sh reads (.start/mcp.log)"
  fi
  printf '%-17s' ''
  route=""
  if python3 "$project/check-xochi.py" --json "$logs/xochi.json" >"$logs/xochi.log" 2>&1; then
    route=$(sed -n 's/.*route: \(.*\); can_solve: \(.*\)$/route \1, can_solve \2/p' "$logs/xochi.log" |
      sed -e 's/ (about [0-9]*s),/,/' -e 's/can_solve True$/can_solve true/' -e 's/can_solve False$/can_solve false/')
  fi
  if [ -n "$route" ]; then
    ok "Xochi 25 USDC: $route"
    prove xochi-preview
  else
    skipped "Xochi preview unavailable; the mock still works (.start/xochi.log)"
  fi
}

# One argument as a single-quoted sh word.
quote() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

# An MCP client config that launches the read-only Web3 server from any folder:
# many clients cannot set a working directory, so the command does the cd, and it
# names the resolved toolchain so the client's own PATH cannot pick another Elixir.
mcp_config() {
  use_toolchain || return 1
  homes=""
  for name in MIX_HOME MIX_ARCHIVES; do
    value=$(recorded "$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')")
    if [ -n "$value" ]; then
      homes="$homes export $name=$(quote "$value") &&"
    else
      homes="$homes unset $name &&"
    fi
  done
  launch="cd $(quote "$package") && export PATH=$(quote "$(recorded path)")\"\${PATH:+:\$PATH}\" MIX_ENV=dev &&$homes exec $(quote "$elixir_bin/mix") run --no-start --no-compile $(quote "$project/web3-mcp.exs")"
  python3 -I -c 'import json, sys; print(json.dumps({"mcpServers": {"raxol-web3": {"command": "sh", "args": ["-c", sys.argv[1]]}}}, indent=2))' "$launch"
}

# report.json holds what the setup prompt asks the agent to report, and keeps
# what ran apart from what is pending. With a step name and its log, the run
# failed there; ran still lists only steps with evidence.
write_report() {
  python3 -I - "$project" "$revision" "$(locked_raxol)" "$run_id" "${1:-}" "${2:-}" <<'PY'
import json
import re
import sys
from pathlib import Path

project, revision, raxol, run_id = Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4]
failed_step, failed_log = sys.argv[5], sys.argv[6]
logs = project / ".start"
STEPS = [
    ("source", "source", "sh start.sh"),
    ("toolchain", "toolchain", "sh start.sh"),
    ("build", "build", "sh start.sh"),
    ("fixture", "fixture", "sh start.sh"),
    ("payouts", "payout round", "sh start.sh payouts"),
    ("chain-reads", "public chain reads", "sh start.sh reads"),
    ("xochi-preview", "Xochi quote preview", "sh start.sh reads"),
    ("image", "local image and offline run", "sh start.sh image"),
]


def evidence(key):
    path = logs / "evidence" / key
    if not path.is_file():
        return None
    return dict(line.split("=", 1) for line in path.read_text().splitlines() if "=" in line)


def read_text(name):
    path = logs / name
    return path.read_text() if path.is_file() else ""


def read_json(name):
    path = logs / name
    return json.loads(path.read_text()) if path.is_file() else None


proof = {key: evidence(key) for key, _, _ in STEPS}
ran = [{"step": label, "at": proof[key].get("at"), "this_run": proof[key].get("run") == run_id}
       for key, label, _ in STEPS if proof[key]]
# Each chain's own outcome, so a skipped chain is never listed as read.
mcp = read_json("mcp.json")
chain_reads = {r["name"]: (f"read from {r.get('source', 'unknown')}, block {r['block']}" if r.get("status") == "read"
                           else f"skipped ({r.get('reason', 'upstream error')}), not a read")
               for r in (mcp or {}).get("reads", {}).values()} or "not run"
for entry in ran:
    if entry["step"] == "public chain reads":
        entry["chains"] = chain_reads
pending = [{"step": label, "run": command} for key, label, command in STEPS if not proof[key]]
pending += [{"step": "Fly deployment", "run": "DEPLOY.md, human only"},
            {"step": "real settlement", "run": "SETTLE.md, human only"}]

toolchain = {}
if proof["toolchain"]:
    toolchain = dict(line.split("=", 1) for line in read_text("toolchain").splitlines() if "=" in line)
fixture = {"35_usdc": "not run", "25_usdc": "not run"}
if proof["fixture"]:
    fixture_log = read_text("fixture.log")
    for amount in ("35", "25"):
        match = re.search(rf"^{amount} USDC: (refused|allowed)", fixture_log, re.M)
        fixture[f"{amount}_usdc"] = match.group(1) if match else "not run"
    receipt = re.search(r"^25 USDC: allowed by Raxol; (\{.*\})$", fixture_log, re.M)
    if receipt:
        fixture["receipt"] = json.loads(receipt.group(1))
payouts = re.search(r"^payout round: (.*)$", read_text("payouts.log"), re.M) if proof["payouts"] else None

report = {
    "this_run": run_id,
    "failed": {"step": failed_step, "log": failed_log} if failed_step else None,
    "evidence_policy": "A full run clears evidence and reruns every step except the image. "
                       "A subcommand reruns its own step; older evidence stays in ran with this_run false.",
    "revision": revision,
    "raxol": raxol if proof["build"] and raxol else "not built",
    "toolchain": (f"Elixir {toolchain.get('elixir')} on Erlang/OTP {toolchain.get('otp')}"
                  if toolchain.get("elixir") and toolchain.get("otp") else "not checked"),
    "fixture": fixture,
    "payout_round": payouts.group(1) if payouts else "not run",
    "chain_reads": chain_reads,
    "mcp": mcp or "not run",
    "xochi_preview": read_json("xochi.json") or "not run",
    "image": read_json("image.json") if proof["image"] else "not run (sh start.sh image)",
    "ran": ran,
    "pending": pending,
}
(project / "report.json").write_text(json.dumps(report, indent=2) + "\n")
PY
}

next_steps() {
  printf '\nNext\n'
  printf '  %-22s %s\n' \
    "sh start.sh payouts" "rerun after editing payout-panel.exs (about 2s)" \
    "sh start.sh reads" "retry the chain reads and the Xochi preview" \
    "sh start.sh image" "build the container and run it offline" \
    "mcp-config.json" "add 13 read-only chain tools to your MCP client" \
    "SETTLE.md, DEPLOY.md" "real settlement and Fly: for the human, not the agent"
}

# Docker builds only setup.sh and contributor.exs (.dockerignore keeps the rest out).
build_image() {
  steps=2
  step 1 image
  forget image
  rm -f "$logs/image.json"
  if ! docker info >/dev/null 2>&1; then
    printf '%s\n' "check-image: Docker is not running" "fix: start Docker, then rerun sh start.sh image" >"$logs/image.log"
    fail "$logs/image.log"
  fi
  started=$(date +%s)
  docker build -t axol-contributor:fixture "$project" >"$logs/image.log" 2>&1 || fail "$logs/image.log"
  ok "axol-contributor:fixture, $(docker image ls axol-contributor:fixture --format '{{.Size}}') ($(($(date +%s) - started))s)"
  step 2 offline
  docker run --rm --network none axol-contributor:fixture >"$logs/image-run.log" 2>>"$logs/image.log" ||
    fail "$logs/image.log"
  both_decisions "$logs/image-run.log" || fail "$logs/image-run.log"
  ok "docker run --network none: 35 USDC refused, 25 USDC allowed"
  printf '{"result": "ok: both fixture decisions offline", "size": "%s"}\n' \
    "$(docker image ls axol-contributor:fixture --format '{{.Size}}')" >"$logs/image.json"
  prove image
  write_report
}

main() {
  # One meaning of "the project" for the whole run: the folder holding start.sh,
  # whichever folder it was called from. setup.sh works in the current folder.
  cd "$project"
  mkdir -p "$logs"
  case "${1:-all}" in
    all)
      # A full run starts from no evidence; the image keeps its own until rebuilt.
      forget source toolchain build fixture payouts chain-reads xochi-preview
      rm -f "$logs/mcp.json" "$logs/xochi.json" "$project/mcp-config.json"
      started=$(date +%s)
      fetch_source
      check_toolchain
      build
      run_fixture
      run_payouts 5
      live_reads 6
      write_report
      current=mcp-config
      mcp_config >"$logs/mcp-config.json" 2>"$logs/mcp-config.log" || fail "$logs/mcp-config.log"
      mv "$logs/mcp-config.json" "$project/mcp-config.json"
      printf '\nDone in %ss. Results: report.json. Logs: .start/\n' "$(($(date +%s) - started))"
      next_steps
      ;;
    payouts)
      steps=1
      run_payouts 1
      write_report
      ;;
    reads)
      steps=1
      live_reads 1
      write_report
      ;;
    image) build_image ;;
    mcp-config)
      [ -f "$logs/toolchain" ] || {
        printf 'no build found; run sh start.sh first\n' >&2
        exit 1
      }
      mcp_config
      ;;
    *)
      printf 'usage: sh start.sh [all|payouts|reads|image|mcp-config]\n' >&2
      exit 2
      ;;
  esac
}

main "$@"
