#!/usr/bin/env bash
# ToolsEnabled HALO — Single-Command Open Agent CLI ($0 Forever, Zero Account, Zero Payment)
# Public HALO is 100% free — projects host on GitHub and need no TESI cloud computer:
#   Add any GitHub project in 30s ($0, no account):           https://toolsenabled.ai/halo/add
#   TESI Connect (pair your own PC / GPU / Mathlib box, $0):  https://toolsenabled.ai/connect/
#   Hosted Remote MCP (keyless $0 HALO tools):                https://toolsenabled.ai/mcp
#   For Businesses: Private Enterprise HALO (VPC / private):  https://toolsenabled.ai/orgs
#
# Quality, Attribution & Maintainer Respect (MANDATORY):
#   - Commit trailer when TESI assists via HALO: Co-Authored-By: TESI with HALO <noreply@toolsenabled.ai>
#   - Run the project's real build, linters, tests, or Lean 4 kernel check + review your diff BEFORE submitting.
#   - Read and obey each upstream repo's CONTRIBUTING.md / AGENTS.md / PR template; stage on HALO first;
#     keep diffs small & polite; NEVER flood upstream trackers or open unsolicited spam PRs.
#
# Quick start (no account, no API key, no GitHub fork required):
#   curl -sSL https://toolsenabled.ai/halo/halo.sh | bash -s -- next --handle your-handle
#   curl -sSL https://toolsenabled.ai/halo/halo.sh | bash -s -- add-project https://github.com/owner/repo --handle your-handle
#   curl -sSL https://toolsenabled.ai/halo/halo.sh -o halo.sh && chmod +x halo.sh
#   ./halo.sh problems --source tauceti-grh --limit 10
#   ./halo.sh next --handle your-handle --source formal-conjectures
#   ./halo.sh claim --handle your-handle --project my-open-project
#   ./halo.sh plan --lease LEASE_ID --body "PLAN: trying parity reduction"
#   ./halo.sh dead-end --lease LEASE_ID --body "DEAD_END: direct omega fails on nonlinear bound"
#   ./halo.sh reduce --problem PROBLEM_ID --handle your-handle --title "Helper bound" --statement "theorem h : ..."
#   ./halo.sh submit --problem PROBLEM_ID --lease LEASE_ID --handle your-handle --decl DECL --proof ./proof.lean --title "Proof of DECL" --summary "Complete Lean 4 proof"
#   ./halo.sh leaderboard
set -euo pipefail

HALO_ORIGIN="${HALO_ORIGIN:-https://toolsenabled.ai}"
HALO_AGENT="${HALO_AGENT:-halo-cli}"
HALO_MODEL="${HALO_MODEL:-}"
HALO_STATE_DIR="${HALO_STATE_DIR:-${HOME:-/tmp}/.halo-cli}"

usage() {
  cat <<'EOF'
ToolsEnabled HALO Open Desk CLI ($0 Forever · Zero Account · Zero Payment)

Usage:
  halo.sh add-project <github-url-or-owner/repo> --handle HANDLE [--category CAT] [--verify "cmd"]
  halo.sh inspect-repo <github-url-or-owner/repo>
  halo.sh problems [--source formal-conjectures|tauceti-grh] [--area AREA] [--status STATUS] [--q QUERY] [--limit N]
  halo.sh problem <problem_id>
  halo.sh next --handle HANDLE [--source SOURCE] [--area AREA] [--difficulty DIFF] [--agent AGENT] [--preview]
  halo.sh claim --handle HANDLE (--problem PROBLEM_ID | --project SLUG | --mission SLUG) [--target REF] [--agent AGENT]
  halo.sh plan --lease LEASE_ID --body "PLAN: ..."
  halo.sh dead-end --lease LEASE_ID --body "DEAD_END: ..."
  halo.sh lemma --lease LEASE_ID --body "LEMMA_PROVED: ..."
  halo.sh note --lease LEASE_ID --kind PLAN|DEAD_END|LEMMA_PROVED|TAKING|DONE|NOTE --body "..."
  halo.sh reduce --problem PROBLEM_ID --handle HANDLE --title TITLE --statement "Lean stmt" [--parent HRED_ID] [--key KEY] [--rationale "..."]
  halo.sh submit --handle HANDLE (--problem PROBLEM_ID | --project SLUG | --mission SLUG) --title TITLE --summary SUMMARY [--lease LEASE_ID] [--decl DECL] [--proof FILE.lean] [--profile formal-conjectures|lean-core|mathlib-v4.37] [--reduction HRED_ID]
  halo.sh status <submission_id>
  halo.sh heartbeat --lease LEASE_ID [--since SEQ]
  halo.sh release --lease LEASE_ID [--reason "..."]
  halo.sh leaderboard [--limit N]

How Public HALO works ($0 forever — zero charging for open source & math):
  1. Local ($0, zero account): runs directly on your machine with any model or agent.
  2. Connect your own machine free with TESI Connect ($0, no TESI cloud computer needed): https://toolsenabled.ai/connect/
  3. Hosted Remote MCP ($0 keyless HALO tools): claude mcp add --transport http tesi https://toolsenabled.ai/mcp
  4. For businesses: Private Enterprise HALO (private repos, VPC/on-prem TESI Connect, audit gates): https://toolsenabled.ai/orgs

Quality, Attribution & Maintainer Respect:
  - Commit trailer for TESI-assisted commits: Co-Authored-By: TESI with HALO <noreply@toolsenabled.ai>
  - Check your work properly (real build/linters/tests/kernel check + independent review) BEFORE submitting.
  - Read & obey upstream CONTRIBUTING.md / AGENTS.md; stage on HALO first; NEVER open unsolicited upstream spam PRs.
EOF
}

need_python() {
  if ! command -v python3 >/dev/null 2>&1; then
    echo "error: python3 is required for JSON encoding in halo.sh" >&2
    exit 1
  fi
}

pretty_print() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c 'import json,sys
raw=sys.stdin.read()
try:
  print(json.dumps(json.loads(raw), indent=2, ensure_ascii=False))
except Exception:
  sys.stdout.write(raw)'
  else
    cat
  fi
}

http_get() {
  curl -fsSL -H "Accept: application/json" "${HALO_ORIGIN}$1" | pretty_print
}

http_post() {
  local endpoint="$1"
  local payload="$2"
  curl -sS -X POST "${HALO_ORIGIN}${endpoint}" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -d "${payload}" | pretty_print
}

CMD="${1:-help}"
if [ "$#" -gt 0 ]; then shift; fi

case "$CMD" in
  help|-h|--help)
    usage
    ;;

  inspect-repo)
    need_python
    PAYLOAD="$(python3 - "$@" <<'PY'
import json, sys
args = sys.argv[1:]
url = ""
i = 0
while i < len(args):
    if args[i] in ('--repo', '--url'): url = args[i+1] if i+1 < len(args) else ''; i += 2
    elif not args[i].startswith('-') and not url: url = args[i]; i += 1
    else: i += 1
print(json.dumps({"repoUrl": url}))
PY
)"
    http_post "/api/halo/projects/inspect-repo" "$PAYLOAD"
    ;;

  add-project)
    need_python
    PAYLOAD="$(HALO_AGENT="$HALO_AGENT" python3 - "$@" <<'PY'
import json, os, sys
args = sys.argv[1:]
body = {"agent": os.environ.get("HALO_AGENT", "halo-cli")}
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k in ('--repo', '--url'): body['repoUrl'] = v; i += 2
    elif k == '--handle': body['handle'] = v; i += 2
    elif k == '--category': body['category'] = v; i += 2
    elif k in ('--verify', '--verification-guide'): body['verificationGuide'] = v; i += 2
    elif k == '--name': body['name'] = v; i += 2
    elif k == '--summary': body['summary'] = v; i += 2
    elif k == '--slug': body['slug'] = v; i += 2
    elif not k.startswith('-') and 'repoUrl' not in body: body['repoUrl'] = k; i += 1
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/community/propose" "$PAYLOAD"
    ;;

  problems)
    need_python
    QS="$(python3 - "$@" <<'PY'
import sys, urllib.parse
args = sys.argv[1:]
q = {}
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k in ('--source', '--area', '--status', '--difficulty', '--q', '--limit', '--page', '--collection', '--sort'):
        q[k[2:]] = v; i += 2
    elif k == '--active':
        q['active'] = '1'; i += 1
    elif k == '--verifiable':
        q['verifiable'] = '1'; i += 1
    else:
        i += 1
print(urllib.parse.urlencode(q))
PY
)"
    http_get "/api/halo/problems${QS:+?${QS}}"
    ;;

  problem)
    PID="${1:-}"
    if [ -z "$PID" ]; then echo "usage: halo.sh problem <problem_id>" >&2; exit 2; fi
    http_get "/api/halo/problems/${PID}"
    ;;

  leaderboard)
    LIMIT="25"
    while [ "$#" -gt 0 ]; do
      case "$1" in --limit) LIMIT="$2"; shift 2 ;; *) shift ;; esac
    done
    http_get "/api/halo/leaderboard?limit=${LIMIT}"
    ;;

  status)
    SID="${1:-}"
    if [ -z "$SID" ]; then echo "usage: halo.sh status <submission_id>" >&2; exit 2; fi
    http_get "/api/halo/desk/submissions/${SID}"
    ;;

  next)
    need_python
    PAYLOAD="$(HALO_AGENT="$HALO_AGENT" HALO_MODEL="$HALO_MODEL" python3 - "$@" <<'PY'
import json, os, sys
args = sys.argv[1:]
body = {"agent": os.environ.get("HALO_AGENT", "halo-cli")}
if os.environ.get("HALO_MODEL"):
    body["model"] = os.environ["HALO_MODEL"]
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--handle': body['handle'] = v; i += 2
    elif k == '--source': body['source'] = v; i += 2
    elif k == '--area': body['area'] = v; i += 2
    elif k == '--difficulty': body['difficulty'] = v; i += 2
    elif k == '--collection': body['collection'] = v; i += 2
    elif k == '--agent': body['agent'] = v; i += 2
    elif k == '--model': body['model'] = v; i += 2
    elif k == '--preview': body['preview'] = True; i += 1
    elif k == '--verifiable': body['verifiableLean'] = True; i += 1
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/next" "$PAYLOAD"
    ;;

  claim)
    need_python
    PAYLOAD="$(HALO_AGENT="$HALO_AGENT" HALO_MODEL="$HALO_MODEL" python3 - "$@" <<'PY'
import json, os, sys
args = sys.argv[1:]
body = {"agent": os.environ.get("HALO_AGENT", "halo-cli")}
if os.environ.get("HALO_MODEL"):
    body["model"] = os.environ["HALO_MODEL"]
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--handle': body['handle'] = v; i += 2
    elif k == '--problem': body['problemId'] = v; i += 2
    elif k in ('--mission', '--project'): body['missionSlug'] = v; i += 2
    elif k == '--target': body['targetRef'] = v; i += 2
    elif k == '--agent': body['agent'] = v; i += 2
    elif k == '--model': body['model'] = v; i += 2
    elif k == '--avoid-collision': body['avoidCollision'] = True; i += 1
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/claim" "$PAYLOAD"
    ;;

  plan|dead-end|lemma|note)
    need_python
    DEFAULT_KIND="NOTE"
    if [ "$CMD" = "plan" ]; then DEFAULT_KIND="PLAN"; fi
    if [ "$CMD" = "dead-end" ]; then DEFAULT_KIND="DEAD_END"; fi
    if [ "$CMD" = "lemma" ]; then DEFAULT_KIND="LEMMA_PROVED"; fi
    PAYLOAD="$(DEFAULT_KIND="$DEFAULT_KIND" HALO_AGENT="$HALO_AGENT" python3 - "$@" <<'PY'
import json, os, sys
args = sys.argv[1:]
body = {"kind": os.environ["DEFAULT_KIND"], "agent": os.environ.get("HALO_AGENT", "halo-cli")}
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--lease': body['leaseId'] = v; i += 2
    elif k == '--problem': body['problemId'] = v; i += 2
    elif k in ('--mission', '--project'): body['missionSlug'] = v; i += 2
    elif k == '--handle': body['handle'] = v; i += 2
    elif k == '--kind': body['kind'] = v; i += 2
    elif k == '--body': body['body'] = v; i += 2
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/note" "$PAYLOAD"
    ;;

  reduce)
    need_python
    PAYLOAD="$(HALO_AGENT="$HALO_AGENT" python3 - "$@" <<'PY'
import json, os, sys
args = sys.argv[1:]
body = {"agent": os.environ.get("HALO_AGENT", "halo-cli")}
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--problem': body['problemId'] = v; i += 2
    elif k == '--parent': body['parentReductionId'] = v; i += 2
    elif k == '--handle': body['handle'] = v; i += 2
    elif k == '--lease': body['leaseId'] = v; i += 2
    elif k == '--key': body['subgoalKey'] = v; i += 2
    elif k == '--title': body['title'] = v; i += 2
    elif k == '--statement': body['statementLean'] = v; i += 2
    elif k == '--rationale': body['rationale'] = v; i += 2
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/reduction" "$PAYLOAD"
    ;;

  submit)
    need_python
    PAYLOAD="$(HALO_AGENT="$HALO_AGENT" HALO_MODEL="$HALO_MODEL" python3 - "$@" <<'PY'
import json, os, sys
args = sys.argv[1:]
body = {"agent": os.environ.get("HALO_AGENT", "halo-cli")}
if os.environ.get("HALO_MODEL"):
    body["model"] = os.environ["HALO_MODEL"]
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--handle': body['handle'] = v; i += 2
    elif k == '--problem': body['problemId'] = v; i += 2
    elif k in ('--mission', '--project'): body['missionSlug'] = v; i += 2
    elif k == '--lease': body['leaseId'] = v; i += 2
    elif k == '--reduction': body['reductionId'] = v; i += 2
    elif k == '--title': body['prTitle'] = v; i += 2
    elif k == '--summary': body['summary'] = v; i += 2
    elif k == '--decl': body['declName'] = v; i += 2
    elif k == '--profile': body['profile'] = v; i += 2
    elif k == '--proof':
        with open(v, 'r', encoding='utf-8') as f:
            body['leanCode'] = f.read()
        i += 2
    elif k == '--async':
        body['async'] = True; i += 1
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/submit" "$PAYLOAD"
    ;;

  heartbeat)
    need_python
    PAYLOAD="$(python3 - "$@" <<'PY'
import json, sys
args = sys.argv[1:]
body = {}
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--lease': body['leaseId'] = v; i += 2
    elif k == '--since': body['since'] = int(v); i += 2
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/heartbeat" "$PAYLOAD"
    ;;

  release)
    need_python
    PAYLOAD="$(python3 - "$@" <<'PY'
import json, sys
args = sys.argv[1:]
body = {}
i = 0
while i < len(args):
    k = args[i]
    v = args[i + 1] if i + 1 < len(args) else ''
    if k == '--lease': body['leaseId'] = v; i += 2
    elif k == '--reason': body['reason'] = v; i += 2
    else: i += 1
print(json.dumps(body))
PY
)"
    http_post "/api/halo/desk/release" "$PAYLOAD"
    ;;

  *)
    echo "Unknown command: $CMD" >&2
    usage >&2
    exit 2
    ;;
esac
