# ═══════════════════════════════════════════════════════════════════════════════
# 🦌 DEERFLOW — Makefile
#
# Build automation for the Deerflow Framework.
# Every target corresponds to a real command — no placeholders, no stubs.
#
# Usage:
#   make <target>        Run a specific target
#   make help            Show all available targets
#   make quality-gate    Run the full quality gate pipeline
#
# ═══════════════════════════════════════════════════════════════════════════════

# ─── Configuration ───────────────────────────────────────────────────────────

NODE_BIN     := npx
NPM          := npm
DOCKER       := docker
GIT          := git
SCRIPTS_DIR  := scripts
REPORT_DIR   := .agent/reports
COVERAGE_DIR := coverage

# Version file for release management
VERSION_FILE := package.json

# Docker image naming
DOCKER_IMAGE ?= deerflow
DOCKER_TAG   ?= latest

# Test configuration
VITEST       := npx vitest
COVERAGE     := --coverage

# ─── Phony Targets ───────────────────────────────────────────────────────────

.PHONY: enforce \
        quality-gate agent-verify \
        fix \
        test test:unit test:integration test:e2e test:watch \
        lint lint:fix lint:perf \
        type-check \
        format format:check \
        security \
        docker:build docker:up docker:down docker:logs docker:ps \
        release:patch release:minor release:major \
        clean fresh \
        help

# ─── Enforcement ─────────────────────────────────────────────────────────────

## enforce: Install all enforcement tools (husky, eslint, prettier, vitest, commitlint)
enforce:
        @echo "🦌 Installing Deerflow enforcement tools..."
        $(NPM) install --save-dev \
                husky \
                eslint \
                @typescript-eslint/eslint-plugin \
                @typescript-eslint/parser \
                eslint-config-prettier \
                eslint-plugin-import \
                eslint-plugin-unicorn \
                eslint-plugin-security \
                prettier \
                vitest \
                @vitest/coverage-istanbul \
                commitlint \
                @commitlint/cli \
                @commitlint/config-conventional \
                zod \
                typescript
        @echo "🔧 Setting up Husky git hooks..."
        $(NPM) exec -- husky install
        @echo "✅ Enforcement tools installed. Git hooks are active."

# ─── Quality Gate ────────────────────────────────────────────────────────────

## quality-gate: Run full quality gate pipeline (9 gates, zero tolerance)
quality-gate:
        @echo "🦌 Running Deerflow Quality Gate..."
        @bash $(SCRIPTS_DIR)/quality-gate.sh

## agent-verify: Verify agent followed all AGENT_RULES (self-check checklist)
agent-verify:
        @echo "🦌 Verifying agent compliance with AGENT_RULES.md..."
        @echo ""
        @echo "── Checking Rule 1: Quality gate was run ──"
        @test -f $(REPORT_DIR)/quality-report.json && echo "  ✓ Quality report exists" || echo "  ✗ No quality report found — run make quality-gate"
        @echo ""
        @echo "── Checking Rule 2: No mock data in production ──"
        @rg -l "mock|Mock|MOCK|fixture|dummy|Dummy|DUMMY|placeholder|Placeholder|PLACEHOLDER|sample_data|test_data" src/ --glob '!*.test.ts' --glob '!*.spec.ts' --glob '!__tests__/**' --glob '!__fixtures__/**' 2>/dev/null && echo "  ✗ Mock data patterns found in production code" || echo "  ✓ No mock data patterns in production code"
        @echo ""
        @echo "── Checking Rule 3: No 'any' types ──"
        @rg -l ": any\b" src/ --glob '!*.d.ts' 2>/dev/null && echo "  ✗ 'any' type found in source files" || echo "  ✓ No 'any' types in source files"
        @echo ""
        @echo "── Checking Rule 5: Test coverage ──"
        @test -d $(COVERAGE_DIR) && echo "  ✓ Coverage directory exists" || echo "  ✗ No coverage directory — run make test"
        @echo ""
        @echo "── Checking Rule 6: No hardcoded secrets ──"
        @rg -l "password\s*=\s*['\"][^'\"]+['\"]|api_key\s*=\s*['\"][^'\"]+['\"]|secret\s*=\s*['\"][^'\"]+['\"]" src/ --glob '!*.test.ts' --glob '!*.spec.ts' 2>/dev/null && echo "  ✗ Potential hardcoded secrets found" || echo "  ✓ No hardcoded secrets detected"
        @echo ""
        @echo "── Checking Rule 9: Conventional commits ──"
        @$(GIT) log --oneline -10 2>/dev/null | grep -E "^[a-f0-9]+ (feat|fix|docs|style|refactor|perf|test|ci|chore|revert)(\(.+\))?:" > /dev/null 2>&1 && echo "  ✓ Recent commits follow conventional format" || echo "  ✗ Recent commits may not follow conventional format"
        @echo ""
        @echo "── Checking Rule 12: No N+1 query patterns ──"
        @rg -l "for\s*\(.*await\s+" src/ --glob '!*.test.ts' 2>/dev/null && echo "  ⚠ Potential N+1 query pattern (await inside loop) found" || echo "  ✓ No obvious N+1 patterns detected"
        @echo ""
        @echo "🦌 Agent verification complete. Fix any ✗ items before proceeding."

# ─── Fix ─────────────────────────────────────────────────────────────────────

## fix: Auto-fix lint and format issues
fix: lint:fix format
        @echo "✅ Lint and format issues fixed."

# ─── Testing ─────────────────────────────────────────────────────────────────

## test: Run all tests with coverage
test:
        $(VITEST) run $(COVERAGE)

## test:unit: Run unit tests only
test:unit:
        $(VITEST) run --reporter=verbose src/**/*.test.ts

## test:integration: Run integration tests only
test:integration:
        $(VITEST) run --reporter=verbose src/**/__tests__/integration/**/*.test.ts

## test:e2e: Run end-to-end tests only
test:e2e:
        $(VITEST) run --reporter=verbose e2e/**/*.test.ts

## test:watch: Run tests in watch mode
test:watch:
        $(VITEST) --watch

# ─── Linting ─────────────────────────────────────────────────────────────────

## lint: Run linter (zero errors, zero warnings)
lint:
        $(NODE_BIN) eslint . --max-warnings=0

## lint:fix: Run linter with auto-fix
lint:fix:
        $(NODE_BIN) eslint . --max-warnings=0 --fix

## lint:perf: Run performance-focused linting checks (rules in eslint.config.js)
lint:perf:
        $(NODE_BIN) eslint . --max-warnings=0

# ─── Type Checking ───────────────────────────────────────────────────────────

## type-check: Run TypeScript type checking (no emit) — checks both src/ and deerflow/
type-check:
        $(NODE_BIN) tsc --noEmit && $(NODE_BIN) tsc --noEmit -p deerflow/tsconfig.json

# ─── Formatting ──────────────────────────────────────────────────────────────

## format: Run prettier to format all files
format:
        $(NODE_BIN) prettier --write "src/**/*.{ts,tsx,js,jsx,json,md}" "*.{ts,js,json,md}"

## format:check: Check formatting without fixing
format:check:
        $(NODE_BIN) prettier --check "src/**/*.{ts,tsx,js,jsx,json,md}" "*.{ts,js,json,md}"

# ─── Security ────────────────────────────────────────────────────────────────

## security: Run security audit (moderate level and above)
security:
        $(NPM) audit --audit-level=moderate

# ─── Docker ──────────────────────────────────────────────────────────────────

## docker:build: Build Docker image using multi-stage Dockerfile
docker:build:
        $(DOCKER) build . --tag $(DOCKER_IMAGE):$(DOCKER_TAG)

## docker:up: Start all services via docker compose
docker:up:
        $(DOCKER) compose up --build --detach

## docker:down: Stop all services
docker:down:
        $(DOCKER) compose down --volumes --remove-orphans

## docker:logs: Tail logs from all services
docker:logs:
        $(DOCKER) compose logs --follow --tail=100

## docker:ps: Show status of all running services
docker:ps:
        $(DOCKER) compose ps

# ─── Release ─────────────────────────────────────────────────────────────────

## release:patch: Bump patch version (x.y.Z → x.y.(Z+1))
release:patch: type-check test
        $(NPM) version patch -m "chore(release): bump version to %s"
        @echo "✅ Patch release created."

## release:minor: Bump minor version (x.Y.z → x.(Y+1).0)
release:minor: type-check test
        $(NPM) version minor -m "chore(release): bump version to %s"
        @echo "✅ Minor release created."

## release:major: Bump major version (X.y.z → (X+1).0.0)
release:major: type-check test
        $(NPM) version major -m "chore(release): bump version to %s"
        @echo "✅ Major release created."

# ─── Cleanup ─────────────────────────────────────────────────────────────────

## clean: Remove build artifacts, coverage, and generated files
clean:
        rm -rf dist/
        rm -rf $(COVERAGE_DIR)/
        rm -rf $(REPORT_DIR)/
        rm -rf node_modules/.cache/
        rm -rf .turbo/
        rm -rf *.tsbuildinfo
        @echo "✅ Build artifacts cleaned."

## fresh: Clean install from scratch (removes node_modules and reinstalls)
fresh: clean
        rm -rf node_modules/
        rm -f package-lock.json
        $(NPM) install
        @echo "✅ Fresh install complete."

# ─── Help ────────────────────────────────────────────────────────────────────

## help: Show all available commands
help:
        @echo ""
        @echo "🦌 DEERFLOW — Available Commands"
        @echo ""
        @echo "── Enforcement ──────────────────────────────────────────"
        @echo "  make enforce          Install all enforcement tools (husky, eslint, prettier, vitest)"
        @echo "  make quality-gate     Run full quality gate pipeline (9 gates, zero tolerance)"
        @echo "  make agent-verify     Verify agent followed all AGENT_RULES"
        @echo ""
        @echo "── Code Quality ─────────────────────────────────────────"
        @echo "  make fix              Auto-fix lint and format issues"
        @echo "  make lint             Run linter (zero errors, zero warnings)"
        @echo "  make lint:fix         Run linter with auto-fix"
        @echo "  make lint:perf        Run performance-focused linting checks"
        @echo "  make type-check       Run TypeScript type checking"
        @echo "  make format           Run prettier to format all files"
        @echo "  make format:check     Check formatting without fixing"
        @echo "  make security         Run security audit (moderate+)"
        @echo ""
        @echo "── Testing ──────────────────────────────────────────────"
        @echo "  make test             Run all tests with coverage"
        @echo "  make test:unit        Run unit tests only"
        @echo "  make test:integration Run integration tests only"
        @echo "  make test:e2e         Run end-to-end tests only"
        @echo "  make test:watch       Run tests in watch mode"
        @echo ""
        @echo "── Docker ───────────────────────────────────────────────"
        @echo "  make docker:build     Build Docker image"
        @echo "  make docker:up        Start all services"
        @echo "  make docker:down      Stop all services"
        @echo "  make docker:logs      Tail logs from all services"
        @echo "  make docker:ps        Show running service status"
        @echo ""
        @echo "── Release ──────────────────────────────────────────────"
        @echo "  make release:patch    Bump patch version (x.y.Z → x.y.Z+1)"
        @echo "  make release:minor    Bump minor version (x.Y.z → x.Y+1.0)"
        @echo "  make release:major    Bump major version (X.y.z → X+1.0.0)"
        @echo ""
        @echo "── Maintenance ──────────────────────────────────────────"
        @echo "  make clean            Remove build artifacts"
        @echo "  make fresh            Clean install from scratch"
        @echo "  make help             Show this help message"
        @echo ""
