# 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 cargo tools..."
    cargo install --locked cargo-watch sea-orm-cli 2>/dev/null || true

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

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

# 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-backend:
    @echo "🔧 Starting Rust backend..."
    cargo watch --ignore frontend --ignore migration -x 'run --bin nxmesh-master'

dev-api: dev-backend

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

dev-ui: dev-frontend

# 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 frontend && bun run build
    @echo "📦 Embedding frontend into backend static files..."
    mkdir -p dist
    cp -r frontend/dist/* dist/ 2>/dev/null || true

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

# Setup database
db-setup:
    @echo "🐘 Setting up PostgreSQL database..."
    just db-wait
    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..."
    sea-orm-cli migrate up

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

# Reset database (drop and recreate)
db-reset:
    @echo "⚠️ Resetting database..."
    sea-orm-cli database 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..."
    sea-orm-cli generate entity \
        --database-url $DATABASE_URL \
        --output-dir crates/nxmesh-master/src/db/entities \
        --with-serde both \
        --with-copy-enums \
        --date-time-crate chrono
    @echo "✅ Entities generated at crates/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 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 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 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

# =============================================================================
# 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 frontend && rm -rf dist node_modules bun.lockb
    rm -rf 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 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 frontend && bunx openapi-typescript /tmp/openapi.json -o src/api/schema.ts
    @echo "✅ API client generated at 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"
