# Common dev / build entry points. Run `just` with no args to list.

# The registry (:8080) is the phone book, the daemon (:7070) runs the tmux
# sessions, and Vite serves the UI at http://localhost:5173 (attach is proxied
# to the daemon; see web/vite.config.ts). Override the secret with MAESTRO_TOKEN.
# Run the full local stack — registry + daemon + web UI; Ctrl-C stops all three.
dev:
    #!/usr/bin/env bash
    set -euo pipefail
    token="${MAESTRO_TOKEN:-devtoken}"
    bin="target/debug/maestro"

    echo "▶ building maestro…"
    cargo build --bin maestro

    pids=()
    cleanup() { echo; echo "▶ stopping stack…"; for p in "${pids[@]:-}"; do kill "$p" 2>/dev/null || true; done; }
    trap cleanup EXIT INT TERM

    echo "▶ registry → http://127.0.0.1:8080"
    MAESTRO_TOKEN="$token" MAESTRO_REGISTRY_BIND_ADDR=127.0.0.1:8080 "$bin" registry &
    pids+=($!)
    # Wait for the registry to accept connections before starting the daemon.
    for _ in $(seq 1 50); do (exec 3<>/dev/tcp/127.0.0.1/8080) 2>/dev/null && break || sleep 0.2; done

    echo "▶ daemon   → ws://127.0.0.1:7070 (id: $(hostname))"
    MAESTRO_TOKEN="$token" \
    MAESTRO_REGISTRY_URL=http://127.0.0.1:8080 \
    MAESTRO_DAEMON_BIND_ADDR=127.0.0.1:7070 \
    MAESTRO_DAEMON_URL=ws://127.0.0.1:7070 \
        "$bin" daemon run &
    pids+=($!)
    for _ in $(seq 1 50); do (exec 3<>/dev/tcp/127.0.0.1/7070) 2>/dev/null && break || sleep 0.2; done

    echo "▶ web UI   → http://localhost:5173  (Ctrl-C to stop everything)"
    pnpm -C web install
    MAESTRO_REGISTRY=http://127.0.0.1:8080 MAESTRO_DAEMON=http://127.0.0.1:7070 \
        pnpm -C web dev

# Build the maestro-web binary together with the SPA bundle it embeds.
web:
    pnpm -C web install --frozen-lockfile
    pnpm -C web build
    cargo build -p maestro-web --release

# Run the web bundle in dev mode against a local daemon — Vite serves the
# frontend with HMR, and `/api/*` is proxied directly to the daemon at
# 127.0.0.1:7070 (or wherever $MAESTRO_REGISTRY points; see vite.config.ts).
web-dev:
    pnpm -C web install
    pnpm -C web dev

# Typecheck the frontend without building.
web-typecheck:
    pnpm -C web install --frozen-lockfile
    pnpm -C web typecheck

# Full workspace build + tests.
test:
    cargo fmt --all -- --check
    cargo clippy --all-targets -- -D warnings
    cargo test --all

# Format every Rust source.
fmt:
    cargo fmt --all
