#!/usr/bin/env bash
# =============================================================================
# RSS2 - Recompila binarios y frontend (sin reinstalar el sistema)
# Usar despues de actualizar el codigo: bash build.sh
# =============================================================================
set -euo pipefail

RSS2_HOME="/opt/rss2"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

export PATH=$PATH:/usr/local/go/bin

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info() { echo -e "${GREEN}[BUILD]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }

# --- Go Backend + Workers ---
if [[ -d "$REPO_ROOT/backend" ]]; then
    info "Compilando backend Go..."
    (cd "$REPO_ROOT/backend" && \
     CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -o "$RSS2_HOME/bin/server" ./cmd/server)
    info "  [OK] server"

    for cmd in scraper discovery wiki_worker topics related; do
        [[ -d "$REPO_ROOT/backend/cmd/$cmd" ]] || continue
        (cd "$REPO_ROOT/backend" && \
         CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -o "$RSS2_HOME/bin/$cmd" "./cmd/$cmd")
        info "  [OK] $cmd"
    done
    # qdrant worker: nombre del binario debe coincidir con el service
    [[ -d "$REPO_ROOT/backend/cmd/qdrant" ]] && \
        (cd "$REPO_ROOT/backend" && \
         CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -o "$RSS2_HOME/bin/qdrant_worker" "./cmd/qdrant")
    info "  [OK] qdrant_worker"
fi

# --- Ingestor Go ---
if [[ -d "$REPO_ROOT/rss-ingestor-go" ]]; then
    info "Compilando ingestor Go..."
    (cd "$REPO_ROOT/rss-ingestor-go" && \
     GOTOOLCHAIN=local CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -o "$RSS2_HOME/bin/ingestor" .)
    info "  [OK] ingestor"
fi

# --- Frontend React ---
if [[ -d "$REPO_ROOT/frontend" ]]; then
    info "Compilando frontend React..."
    (cd "$REPO_ROOT/frontend" && \
     npm install --silent && \
     VITE_API_URL=/api npm run build -- --outDir "$RSS2_HOME/frontend/dist")
    info "  [OK] frontend"
fi

# --- Workers Python ---
info "Sincronizando workers Python..."
rsync -a --delete "$REPO_ROOT/workers/" "$RSS2_HOME/src/workers/"
cp "$REPO_ROOT/entity_config.json" "$RSS2_HOME/src/" 2>/dev/null || true
info "  [OK] workers Python"

chown -R rss2:rss2 "$RSS2_HOME/bin" "$RSS2_HOME/frontend/dist" "$RSS2_HOME/src"

# --- Restart servicios ---
info "Reiniciando servicios..."
GO_SERVICES=(rss2-backend rss2-ingestor rss2-scraper rss2-discovery rss2-wiki rss2-topics rss2-related rss2-qdrant-worker)
PY_SERVICES=(rss2-langdetect rss2-translation-scheduler rss2-translator rss2-embeddings rss2-ner rss2-cluster rss2-categorizer)

for svc in "${GO_SERVICES[@]}" "${PY_SERVICES[@]}"; do
    systemctl is-active --quiet "$svc" && systemctl restart "$svc" && info "  restarted $svc" || true
done

systemctl reload nginx 2>/dev/null || true

info "Build completado."
