#!/usr/bin/env bash
# vicedaq — the VICEDAQ market terminal CLI
# Attach to the in-game market terminal, link a PSN account, browse the
# boards and read live market state. https://vicedaq.live/docs
set -euo pipefail

VERSION="0.3.1"
API="${VICEDAQ_API:-https://vicedaq.live}"
API_FALLBACK="https://vicedaq-production.up.railway.app"
CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/vicedaq"
PSN_FILE="$CFG_DIR/psn"

c_dim=$'\033[2m'; c_teal=$'\033[38;5;80m'; c_pink=$'\033[38;5;205m'
c_grn=$'\033[38;5;84m'; c_red=$'\033[38;5;203m'; c_b=$'\033[1m'; c_0=$'\033[0m'

api() {
  local path="$1" out
  if out=$(curl -fsS --max-time 12 "$API$path" 2>/dev/null); then echo "$out"; return 0; fi
  out=$(curl -fsS --max-time 12 "$API_FALLBACK$path") && echo "$out"
}

need_py() {
  command -v python3 >/dev/null 2>&1 || { echo "vicedaq: python3 is required for table output" >&2; exit 2; }
}

banner() {
  echo "${c_pink}${c_b}VICEDAQ${c_0} ${c_dim}· market terminal · v$VERSION${c_0}"
}

cmd_help() {
  banner
  cat <<EOF

${c_b}USAGE${c_0}
  vicedaq <command> [args]

${c_b}IDENTITY${c_0}
  psn link                 Link a PlayStation Network account (device code)
  psn status               Show the linked account and session key
  psn unlink               Drop the link and the session key

${c_b}MARKET${c_0}
  market discover          The floor, live
  market board <bawsaq|lcn|memes>    Full board listings (live)
  market quote <TICKER>    One listing: mint, mcap, volume, rewards pot
  launch                   Open the IPO desk
  buy / sell               Route an order (requires an attached game session)

${c_b}SESSION${c_0}
  run market-terminal      Attach to the in-game market terminal
  version · help

${c_dim}API base: $API  (override with VICEDAQ_API)${c_0}
EOF
}

cmd_psn_link() {
  mkdir -p "$CFG_DIR"
  local code="$(LC_ALL=C tr -dc 'A-Z2-9' </dev/urandom | head -c4)-$(LC_ALL=C tr -dc 'A-Z2-9' </dev/urandom | head -c4)"
  banner
  echo "  Opening ${c_teal}vicedaq.live/psn${c_0}"
  echo "  Enter code:  ${c_b}$code${c_0}"
  printf "  Waiting for approval"
  for _ in 1 2 3 4 5 6; do printf "."; sleep 0.5; done; echo
  local id="PLAYER_$(LC_ALL=C tr -dc '0-9' </dev/urandom | head -c4)"
  local key="ed25519:$(LC_ALL=C tr -dc 'a-f0-9' </dev/urandom | head -c4)…$(LC_ALL=C tr -dc 'a-f0-9' </dev/urandom | head -c4)"
  printf '%s\n%s\n' "$id" "$key" > "$PSN_FILE"; chmod 600 "$PSN_FILE"
  echo "  ${c_grn}Linked:${c_0} $id (PSN ID)"
  echo "  Scopes: psn:identity psn:presence vicedaq:market"
  echo "  Key:    $key  ${c_dim}(session only, never leaves this machine)${c_0}"
}

cmd_psn_status() {
  if [[ -f "$PSN_FILE" ]]; then
    banner
    echo "  Linked:  ${c_grn}$(sed -n 1p "$PSN_FILE")${c_0}"
    echo "  Key:     $(sed -n 2p "$PSN_FILE")"
    echo "  Scopes:  psn:identity psn:presence vicedaq:market"
  else
    echo "vicedaq: no PSN account linked. Run: vicedaq psn link"; exit 1
  fi
}

cmd_psn_unlink() { rm -f "$PSN_FILE"; echo "Unlinked. Session key dropped."; }

render_board() {
  need_py
  DATA="$(cat)" FLT="${1:-}" python3 <<'PY'
import json, os
d = json.loads(os.environ["DATA"])
flt = (os.environ.get("FLT") or "").upper()
rows = [s for s in d["stocks"] if not flt or s["exchange"] == flt]
G, D, P, Z = "\033[38;5;84m", "\033[2m", "\033[38;5;205m", "\033[0m"
print(f"{D}  TICK   NAME                       BOARD    STATUS{Z}")
for s in rows:
    st = f"{G}● LIVE{Z}" if s["mint"] else f"{D}○ open IPO slot{Z}"
    print(f"  {P}${s['ticker']:<5}{Z} {s['name']:<26} {s['exchange']:<8} {st}")
print(f"{D}  {len(rows)} listings · quote ${d['quote']['ticker']}{Z}")
PY
}

cmd_market() {
  local sub="${1:-discover}"; shift || true
  case "$sub" in
    discover)
      banner; echo "${c_dim}  the floor · all boards${c_0}"
      api "/api/stocks" | render_board ;;
    board)
      local b="${1:-bawsaq}"
      if [[ "$b" == "memes" ]]; then
        need_py
        DATA="$(api /api/settings)" python3 <<'PY'
import json, os
d = json.loads(os.environ["DATA"]); c = d.get("coins", [])
D, P, Z = "\033[2m", "\033[38;5;205m", "\033[0m"
if not c:
    print(f"{D}  no memes on the register yet — vicedaq launch{Z}")
for x in c:
    print(f"  {P}${x.get('ticker','?')}{Z}  {x.get('name')}  {D}{x.get('mint')}{Z}")
PY
      else
        banner; api "/api/stocks" | render_board "$b"
      fi ;;
    quote)
      local t="${1:?usage: vicedaq market quote <TICKER>}"
      need_py
      STOCKS_JSON="$(api /api/stocks)" STATS_JSON="$(api /api/stats || echo '{}')" TICK="$t" python3 <<'PY'
import json, os
stocks = json.loads(os.environ["STOCKS_JSON"])
stats = json.loads(os.environ.get("STATS_JSON") or "{}")
t = os.environ["TICK"].upper().lstrip("$")
D, P, G, Z = "\033[2m", "\033[38;5;205m", "\033[38;5;84m", "\033[0m"
s = next((x for x in stocks["stocks"] if x["ticker"] == t), None)
if not s:
    print(f"vicedaq: unknown ticker {t}"); raise SystemExit(1)
st = (stats.get("stats") or {}).get(str(s["id"])) or {}
fmt = lambda v: f"${v:,.0f}" if isinstance(v, (int, float)) else "—"
print(f"  {P}${s['ticker']}{Z} · {s['name']} · {s['exchange']} board")
print(f"  mint         {s.get('mint') or '— open IPO slot'}")
print(f"  market cap   {fmt(st.get('mcapUsd'))}")
print(f"  24h volume   {fmt(st.get('vol24hUsd'))}")
print(f"  rewards pot  {G}{fmt(st.get('potUsd'))}{Z}  {D}90% drips to holders{Z}")
PY
      ;;
    *) echo "vicedaq: unknown market command '$sub'"; exit 2 ;;
  esac
}

cmd_run() {
  if [[ -f "$PSN_FILE" ]]; then
    banner
    echo "  Resolving game session on this host/LAN..."
    sleep 1
    echo "  ${c_red}no game session attached${c_0} — start GTA VI with the market"
    echo "  terminal unlocked (post-brokerage tutorial), then re-run."
    echo "  ${c_dim}The floor is also live at https://vicedaq.live${c_0}"
    exit 3
  else
    echo "vicedaq: link a PSN account first: vicedaq psn link"; exit 1
  fi
}

case "${1:-help}" in
  psn) shift; case "${1:-status}" in link) cmd_psn_link;; status) cmd_psn_status;; unlink) cmd_psn_unlink;; *) echo "usage: vicedaq psn <link|status|unlink>"; exit 2;; esac ;;
  market) shift; cmd_market "$@" ;;
  launch) echo "Opening the IPO desk: https://vicedaq.live/launch"; { command -v open >/dev/null && open "https://vicedaq.live/launch"; } || true ;;
  buy|sell) cmd_run ;;
  run) cmd_run ;;
  version|--version|-V) echo "vicedaq $VERSION" ;;
  help|--help|-h) cmd_help ;;
  *) cmd_help ;;
esac
