#!/usr/bin/env bash
set -e

MINER_KEY="${1:-}"
BASE_URL="https://explorer.malairtebitcoin.com/downloads"
INSTALL_DIR="/usr/local/bin"
DATA_DIR="$HOME/.malairte-node"
PLIST_DIR="$HOME/Library/LaunchAgents"
PLIST_FILE="$PLIST_DIR/com.malairte.malairte-node.plist"

GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[1;33m'; AMBER='\033[0;33m'; BOLD='\033[1m'; NC='\033[0m'

echo ""
echo "  Malairte Blockchain Node — macOS Setup"
echo ""

if [ -z "$MINER_KEY" ]; then
  echo -e "${RED}Error: Miner private key required.${NC}"
  echo "Usage: bash setup-macos.sh <YOUR_PRIVATE_KEY_HEX>"
  echo "Get your key from https://explorer.malairtebitcoin.com/onboarding"
  exit 1
fi

ARCH=$(uname -m)
case "$ARCH" in
  x86_64)  BINARY="malairte-node-darwin-amd64"  ; CLIBINARY="malairte-cli-darwin-amd64"  ;;
  arm64)   BINARY="malairte-node-darwin-arm64"  ; CLIBINARY="malairte-cli-darwin-arm64"  ;;
  *) echo -e "${RED}Unsupported architecture: $ARCH${NC}"; exit 1 ;;
esac

echo "Detected: macOS $ARCH"
echo ""

if ! command -v curl &>/dev/null; then
  echo -e "${RED}Error: curl is required.${NC}"; exit 1
fi

echo "→ Downloading $BINARY..."
sudo curl -fsSL "$BASE_URL/$BINARY" -o "$INSTALL_DIR/malairte-node"
sudo chmod +x "$INSTALL_DIR/malairte-node"
echo -e "${GREEN}✓ malairte-node installed${NC}"

echo "→ Downloading $CLIBINARY..."
sudo curl -fsSL "$BASE_URL/$CLIBINARY" -o "$INSTALL_DIR/malairte-cli"
sudo chmod +x "$INSTALL_DIR/malairte-cli"
echo -e "${GREEN}✓ malairte-cli installed${NC}"

echo "→ Creating data directory..."
mkdir -p "$DATA_DIR/mainnet/chaindata"
echo -e "${GREEN}✓ Data directory: $DATA_DIR${NC}"

echo "→ Removing quarantine attribute..."
sudo xattr -dr com.apple.quarantine "$INSTALL_DIR/malairte-node" 2>/dev/null || true
sudo xattr -dr com.apple.quarantine "$INSTALL_DIR/malairte-cli" 2>/dev/null || true

echo "→ Creating LaunchAgent..."
mkdir -p "$PLIST_DIR"
cat > "$PLIST_FILE" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.malairte.malairte-node</string>
    <key>ProgramArguments</key>
    <array>
        <string>$INSTALL_DIR/malairte-node</string>
        <string>--data-dir=$DATA_DIR</string>
        <string>--network=mainnet</string>
        <string>--mine</string>
        <string>--miner-key=$MINER_KEY</string>
        <string>--seeds=104.192.5.197:9333</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>$DATA_DIR/malairte-node.log</string>
    <key>StandardErrorPath</key>
    <string>$DATA_DIR/malairte-node.log</string>
</dict>
</plist>
EOF

launchctl load "$PLIST_FILE"
echo -e "${GREEN}✓ LaunchAgent loaded — node starts automatically on login${NC}"

# ── Install mlrt-status helper ────────────────────────────────────────────────
sudo tee /usr/local/bin/mlrt-status > /dev/null <<'STATUSEOF'
#!/usr/bin/env bash
GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[1;33m'; AMBER='\033[0;33m'; BOLD='\033[1m'; NC='\033[0m'
PLIST="$HOME/Library/LaunchAgents/com.malairte.malairte-node.plist"
DATA_DIR="$HOME/.malairte-node"

echo ""
echo -e "${BOLD}  Malairte Node Status${NC}"
echo "  ─────────────────────────────────────"

# Service state
if launchctl list 2>/dev/null | grep -q "com.malairte.malairte-node"; then
  PID=$(launchctl list com.malairte.malairte-node 2>/dev/null | grep '"PID"' | awk '{print $3}' | tr -d ',')
  if [ -n "$PID" ] && [ "$PID" != "0" ]; then
    echo -e "  ${GREEN}●${NC} Node:    ${GREEN}Running${NC}  (PID $PID)"
    echo -e "  ${AMBER}⛏${NC}  Mining:  ${AMBER}CPU  •  MLRT${NC}"
  else
    echo -e "  ${YELLOW}●${NC} Node:    ${YELLOW}Loaded (starting...)${NC}"
  fi
else
  echo -e "  ${RED}●${NC} Node:    ${RED}Not running${NC}"
fi

# Binary versions
if command -v malairte-node &>/dev/null; then
  echo -e "  ◦ malairte-node:   $(malairte-node --version 2>/dev/null || echo 'installed')"
fi
if command -v malairte-cli &>/dev/null; then
  echo -e "  ◦ malairte-cli:  $(malairte-cli --version 2>/dev/null || echo 'installed')"
fi

# Log tail
if [ -f "$DATA_DIR/malairte-node.log" ]; then
  echo ""
  echo -e "${BOLD}  Recent log:${NC}"
  tail -5 "$DATA_DIR/malairte-node.log" | sed 's/^/    /'
fi

echo ""
echo "  Commands:"
echo "    mlrt-status                  — show this screen"
echo "    launchctl unload   $PLIST"
echo "    launchctl load     $PLIST"
echo "    tail -f $DATA_DIR/malairte-node.log"
echo ""
STATUSEOF
sudo chmod +x /usr/local/bin/mlrt-status

# ── Live status check ─────────────────────────────────────────────────────────
echo ""
echo "→ Waiting for node to start..."
sleep 3

echo ""
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if launchctl list 2>/dev/null | grep -q "com.malairte.malairte-node"; then
  PID=$(launchctl list com.malairte.malairte-node 2>/dev/null | grep '"PID"' | awk '{print $3}' | tr -d ',')
  if [ -n "$PID" ] && [ "$PID" != "0" ]; then
    echo -e "  ${GREEN}● Node: Running  (PID $PID)${NC}"
    echo -e "  ${AMBER}⛏  CPU Mining  •  MLRT${NC}"
  else
    echo -e "  ${YELLOW}● Node: Loaded — starting up...${NC}"
  fi
else
  echo -e "  ${RED}● Node: Not running — check logs below${NC}"
fi

echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "  Run ${BOLD}mlrt-status${NC} anytime to check the node"
echo "  View logs:  tail -f $DATA_DIR/malairte-node.log"
echo "  Explorer:   https://explorer.malairtebitcoin.com"
echo ""
