#!/usr/bin/env bash
# =============================================================================
# atlilith V3 platform — ./run command
# =============================================================================
#
# Usage:
#   ./run test:infra:up   Start ephemeral test datastores (PG + MinIO + Mailpit)
#   ./run test:infra:down Stop ephemeral test datastores
#   ./run dev:proxy        Start Caddy reverse proxy
#   ./run dev:proxy:stop   Stop Caddy
#   ./run dev              Start everything (infra + proxy + all services)
#   ./run dev:stop         Stop everything
#   ./run dev:status       Health-check all services
#   ./run dev:logs [svc]   View logs
#   ./run build            Build all workspace packages
#   ./run typecheck        tsc --noEmit across the monorepo
#   ./run deploy:<svc>     Trigger a service deployment via Forgejo Actions CI
#
# Single source of truth for ports: @platform/infrastructure/ports.yaml
# (consumed at runtime via @lilith/service-addresses.getServicePort())

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")" && pwd)"
INFRA_DIR="$REPO_ROOT/@platform/infrastructure"

# Ports are read at runtime via @lilith/service-addresses; no .env.ports needed.

# V3 has NO dev DBs — frontends call prod APIs on black (atlilith.api, port 3060).
# These compose files exist only for ephemeral TEST runs (per CLAUDE.md line 39).
TEST_DOCKER_FILES=(
    "$INFRA_DIR/test/compose.platform-db.yml"
    "$INFRA_DIR/test/compose.platform-minio.yml"
    "$INFRA_DIR/test/compose.platform-mail.yml"
)

cmd="${1:-help}"

case "$cmd" in
    dev:infra)
        cat <<MSG >&2
V3 has no dev infrastructure. Frontends call production APIs on black
(atlilith.api :3060). See CLAUDE.md line 39 and INFRA.md §3.

For ephemeral test containers (CI / local test runs), use:
  ./run test:infra:up
  ./run test:infra:down
MSG
        exit 2
        ;;
    test:infra:up)
        for f in "${TEST_DOCKER_FILES[@]}"; do
            echo "==> starting $(basename "$f")"
            docker compose -f "$f" up -d
        done
        ;;
    test:infra:down)
        for f in "${TEST_DOCKER_FILES[@]}"; do
            echo "==> stopping $(basename "$f")"
            docker compose -f "$f" down
        done
        ;;
    dev:proxy)
        echo "==> starting Caddy"
        caddy start \
            --config "$INFRA_DIR/Caddyfile.local" \
            --pidfile "/tmp/atlilith-caddy.pid"
        ;;
    dev:proxy:stop)
        if [ -f /tmp/atlilith-caddy.pid ]; then
            kill "$(cat /tmp/atlilith-caddy.pid)" 2>/dev/null || true
            rm -f /tmp/atlilith-caddy.pid
            echo "caddy stopped"
        else
            echo "caddy not running (no pidfile)"
        fi
        ;;
    dev)
        "$0" dev:proxy
        # V3 dev environment: Caddy + frontends that hit prod APIs on black.
        # No dev DBs (see CLAUDE.md). Frontend services launch via their own
        # workspace bun/pnpm dev commands as Phase 6+ ports them.
        echo
        echo "caddy up. Start frontends individually from their feature dirs."
        ;;
    dev:stop)
        "$0" dev:proxy:stop
        ;;
    dev:status)
        echo "==> caddy"
        if [ -f /tmp/atlilith-caddy.pid ] && kill -0 "$(cat /tmp/atlilith-caddy.pid)" 2>/dev/null; then
            echo "running (pid $(cat /tmp/atlilith-caddy.pid))"
        else
            echo "stopped"
        fi
        echo
        echo "==> prod API reachability (black via tunnel)"
        curl -sS -o /dev/null -w "atlilith.api: %{http_code}\n" --max-time 3 http://localhost:3060/health 2>/dev/null || echo "atlilith.api: unreachable (tunnel down?)"
        echo
        echo "==> ephemeral test containers (if any)"
        docker ps --filter "name=atlilith-platform" --format 'table {{.Names}}\t{{.Status}}' 2>/dev/null
        ;;
    dev:logs)
        svc="${2:-}"
        if [ -n "$svc" ]; then
            docker logs -f "atlilith-platform-${svc}"
        else
            echo "Usage: ./run dev:logs <db|minio|mail>"
        fi
        ;;
    build)
        cd "$REPO_ROOT/@platform" && bun run build
        ;;
    typecheck)
        cd "$REPO_ROOT/@platform" && bun run typecheck
        ;;
    manifest)
        shift
        cd @platform && bun run scripts/validate-manifest.ts "$@"
        ;;
    deploy:*)
        target="${cmd#deploy:}"
        echo "==> triggering Forgejo Actions deploy: $target"
        # Forgejo Actions equivalent of `gh workflow run`. Adjust org/repo
        # as actually deployed. Requires FORGEJO_TOKEN.
        curl -sS -H "Authorization: token $FORGEJO_TOKEN" \
            "${FORGEJO_URL}/api/v1/repos/lilith/atlilith/actions/workflows/deploy-${target}.yml/dispatches" \
            -X POST -H "Content-Type: application/json" \
            -d '{"ref":"main"}'
        ;;
    help|*)
        sed -n '/^# Usage:/,/^# Single source/p' "$0" | sed 's/^# \?//'
        ;;
esac
