# NxMesh Development Justfile
# Common commands for development workflow

# Default recipe - shows available commands
default:
    @just --list

# =============================================================================
# Setup Commands
# =============================================================================

# Initial setup - run once after devcontainer creation
setup:
    @echo "🚀 Setting up NxMesh development environment..."
    just setup-rust-tools
    just setup-frontend
    just db-setup
    @echo "✅ Setup complete!"

# Setup Rust dependencies and tools
setup-rust-tools:
    @echo "📦 Installing Rust dependencies..."
    cargo fetch
    @echo "🔧 Installing bin tools"
    cargo install sea-orm-cli@^2.0.0-rc --features "sqlx-postgres runtime-tokio-rustls"
    cargo install cargo-watch

# Setup frontend dependencies
setup-frontend:
    @echo "📦 Installing frontend dependencies..."
    cd apps/nxmesh-frontend && bun install

# =============================================================================
# Development Commands
# =============================================================================

# act
act *ARGS:
    # run act with custom secret-file
    @echo "🎬 Running act with custom secrets file..."
    act --env-file .github/.env --secret-file .github/.secrets.env --var-file .github/.var.env --network host {{ ARGS }}

# Start all services for development
dev:
    @echo "🚀 Starting all development services..."
    just dev-backend &
    just dev-frontend &
    wait

# Start Rust backend with hot reload
dev-master *ARGS:
    @echo "🔧 Starting Rust backend..."
    cargo watch -w apps/nxmesh-master -x 'run --bin nxmesh-master -- {{ ARGS }}'

dev-agent *ARGS:
    @echo "🔧 Starting Rust agent..."
    cargo watch -w apps/nxmesh-agent -x 'run --bin nxmesh-agent -- {{ ARGS }}'

# Start Vite frontend development server
dev-frontend:
    @echo "⚛️ Starting Vite frontend..."
    cd apps/nxmesh-frontend && bun dev

# Start services (called by devcontainer post-start)
start-services:
    @echo "🔧 Ensuring services are ready..."
    just db-wait

# =============================================================================
# Build Commands
# =============================================================================

# Build the entire project (backend + frontend)
build:
    @echo "🏗️ Building entire project..."
    just build-frontend
    just build-backend

# Build Rust backend
build-backend:
    @echo "🔨 Building Rust backend..."
    cargo build --release

# Build frontend and embed into backend
build-frontend:
    @echo "⚛️ Building frontend..."
    cd apps/nxmesh-frontend && bun run build
    @echo "📦 Embedding frontend into backend static files..."
    mkdir -p apps/nxmesh-master/dist
    cp -r apps/nxmesh-frontend/dist/* apps/nxmesh-master/dist/ 2>/dev/null || true

# =============================================================================
# Database Commands
# =============================================================================

db *ARGS:
    cd crates && sea-orm-cli {{ ARGS }}

# Setup database
db-setup:
    @echo "🐘 Setting up PostgreSQL database..."
    just db-wait
    cd crates && sea-orm-cli setup 2>/dev/null || true
    just db-migrate

# Wait for database to be ready
db-wait:
    @echo "⏳ Waiting for PostgreSQL..."
    @until pg_isready -h postgres -p 5432 -U postgres; do sleep 1; done
    @echo "✅ PostgreSQL is ready!"

# Run database migrations
db-migrate:
    @echo "🔄 Running database migrations..."
    cd crates && sea-orm-cli migrate up

# Create new database migration
db-new-migration name:
    @echo "📝 Creating new migration: {{ name }}"
    cd crates && sea-orm-cli migrate generate {{ name }}

# Reset database (drop and recreate)
db-reset:
    @echo "⚠️ Resetting database..."
    cd crates && sea-orm-cli migrate reset

# Connect to database with psql
db-console:
    @echo "🐘 Connecting to PostgreSQL..."
    psql $DATABASE_URL

# Generate SeaORM entities from database schema
db-generate:
    @echo "⚙️ Generating SeaORM entities from database..."
    cd crates && sea-orm-cli generate entity \
        --database-url $DATABASE_URL \
        --output-dir ../apps/nxmesh-master/src/db/entities \
        --with-serde both \
        --with-copy-enums \
        --date-time-crate chrono
    @echo "✅ Entities generated at apps/nxmesh-master/src/db/entities/"

# =============================================================================
# Testing Commands
# =============================================================================

# Run all tests
test:
    @echo "🧪 Running all tests..."
    just test-backend
    just test-frontend

# Run Rust backend tests
test-backend:
    @echo "🦀 Running Rust tests..."
    cargo test

# Run frontend tests
test-frontend:
    @echo "⚛️ Running frontend tests..."
    cd apps/nxmesh-frontend && bun test

# =============================================================================
# Lint & Format Commands
# =============================================================================

# Format all code
fmt:
    @echo "🎨 Formatting code..."
    just fmt-rust
    just fmt-frontend

# Format Rust code
fmt-rust:
    @echo "🦀 Formatting Rust..."
    cargo fmt

# Format frontend code
fmt-frontend:
    @echo "⚛️ Formatting frontend..."
    cd apps/nxmesh-frontend && bun run format

# Lint all code
lint:
    @echo "🔍 Linting code..."
    just lint-rust
    just lint-frontend

# Lint Rust code
lint-rust:
    @echo "🦀 Linting Rust..."
    cargo clippy -- -D warnings

# Lint frontend code
lint-frontend:
    @echo "⚛️ Linting frontend..."
    cd apps/nxmesh-frontend && bun run lint

# =============================================================================
# Docker Commands
# =============================================================================

# Build Docker image for production
docker-build:
    @echo "🐳 Building Docker image..."
    docker build -t nxmesh:latest -f Dockerfile.prod .

# Run production Docker container
docker-run:
    @echo "🐳 Running Docker container..."
    docker run -p 8080:8080 --env-file .env nxmesh:latest

# Build Docker image for CI
docker-build-ci REGISTRY="ghcr.io/nxmesh":
    @echo "🐳 Building Docker image for CI..."
    docker build -t {{ REGISTRY }}/ci:latest -f ./.github/docker/ci.Dockerfile .

# =============================================================================
# Nginx Commands (Shared PID Namespace + Docker Fallback)
# =============================================================================

# Reload nginx configuration (uses shared PID namespace if available)
nginx-reload:
    @echo "🔄 Reloading nginx..."
    bash .devcontainer/scripts/nginx-reload.sh

# Full nginx control via shared PID namespace

# Usage: just nginx-ctl <reload|stop|quit|reopen|upgrade|status>
nginx-ctl cmd="reload":
    @bash .devcontainer/scripts/nginx-ctl.sh {{ cmd }}

# Quick status check
nginx-status:
    @just nginx-ctl status

# Test nginx configuration
nginx-test:
    @echo "🧪 Testing nginx configuration..."
    bash .devcontainer/scripts/nginx-test.sh

# Show nginx logs
nginx-logs:
    @docker logs -f $(docker ps -q -f "ancestor=nginx:alpine" | head -1) 2>/dev/null || echo "Nginx container not found"

# Edit nginx config and reload
nginx-apply:
    @echo "📝 Testing and applying nginx config..."
    just nginx-test
    just nginx-reload

# Copy local nginx config changes to container and reload
nginx-update:
    @echo "📦 Updating nginx configuration..."
    docker cp .devcontainer/nginx/nginx.conf $(docker ps -q -f "ancestor=nginx:alpine" | head -1):/etc/nginx/nginx.conf
    docker cp .devcontainer/nginx/conf.d $(docker ps -q -f "ancestor=nginx:alpine" | head -1):/etc/nginx/
    just nginx-apply

# =============================================================================
# Utility Commands
# =============================================================================

# Clean build artifacts
clean:
    @echo "🧹 Cleaning build artifacts..."
    cargo clean
    cd apps/nxmesh-frontend && rm -rf dist node_modules bun.lockb
    rm -rf apps/nxmesh-master/dist

# Full clean (includes database)
clean-all: clean
    @echo "🧹 Cleaning everything including database..."
    sea-orm-cli database drop 2>/dev/null || true

# Update dependencies
update:
    @echo "📦 Updating dependencies..."
    cargo update
    cd apps/nxmesh-frontend && bun update

# Check project health
health:
    @echo "🏥 Checking project health..."
    @echo "PostgreSQL: $(pg_isready -h postgres -p 5432 -U postgres > /dev/null 2>&1 && echo '✅' || echo '❌')"
    @echo "Nginx: $(curl -sf http://nginx/health > /dev/null 2>&1 && echo '✅' || echo '❌')"
    @echo "Backend: $(curl -sf http://localhost:8080/health > /dev/null 2>&1 && echo '✅' || echo '❌')"
    @echo "Vite Dev: $(curl -sf http://localhost:3000 > /dev/null 2>&1 && echo '✅' || echo '❌')"

# Show logs from all services
logs:
    @echo "📋 Showing logs from all services..."
    cd .devcontainer && docker-compose logs -f

# Generate project documentation
docs:
    @echo "📚 Generating documentation..."
    cargo doc --open 2>/dev/null || cargo doc

# =============================================================================
# API Client Generation Commands
# =============================================================================

# Generate OpenAPI spec from backend (requires backend to be running)
gen-openapi:
    @echo "📋 Generating OpenAPI spec from backend..."
    @curl -s http://localhost:8080/api/openapi.json > /tmp/openapi.json
    @echo "✅ OpenAPI spec saved to /tmp/openapi.json"

# Generate TypeScript API client from OpenAPI spec
gen-api-client:
    @echo "⚡ Generating TypeScript API client..."
    @if [ ! -f /tmp/openapi.json ]; then \
        echo "❌ OpenAPI spec not found. Run 'just gen-openapi' first (backend must be running)."; \
        exit 1; \
    fi
    cd apps/nxmesh-frontend && bunx openapi-typescript /tmp/openapi.json -o src/api/schema.ts
    @echo "✅ API client generated at apps/nxmesh-frontend/src/api/schema.ts"

# Full API generation workflow (start backend, generate spec, generate client, stop backend)
gen-api: start-backend-temp
    @just gen-openapi
    @just gen-api-client
    @echo "✅ API client generation complete!"

# Internal: Start backend temporarily for API generation
start-backend-temp:
    @echo "🔧 Starting backend temporarily..."
    @cargo build --package nxmesh-master
    @cargo run --package nxmesh-master &
    @sleep 5
    @echo "✅ Backend ready"
