.PHONY: help build run clean test lint fmt audit-full install-deps install-tools coverage vulnerability ci

help:
	@echo "Package Security Audit Tool"
	@echo ""
	@echo "Build & Run:"
	@echo "  make build          - Build the audit binary"
	@echo "  make run            - Run audit (requires inventory.json)"
	@echo "  make inventory      - Collect system inventory"
	@echo "  make audit-full     - Collect inventory + run audit"
	@echo ""
	@echo "Testing & Quality:"
	@echo "  make test           - Run unit tests"
	@echo "  make coverage       - Run tests with coverage report"
	@echo "  make lint           - Run all linters"
	@echo "  make fmt            - Format code"
	@echo "  make vulnerability  - Check for known vulnerabilities"
	@echo "  make ci             - Run all CI checks"
	@echo ""
	@echo "Maintenance:"
	@echo "  make install-deps   - Install Go dependencies"
	@echo "  make install-tools  - Install linting & analysis tools"
	@echo "  make clean          - Clean build artifacts"
	@echo ""
	@echo "Quick start:"
	@echo "  make install-tools && make test && make audit-full"

install-tools:
	@echo "Installing analysis tools..."
	go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
	go install golang.org/x/vuln/cmd/govulncheck@latest
	@echo "✓ Tools installed"

install-deps:
	@echo "Installing Go dependencies..."
	go mod download
	go mod tidy

build:
	@echo "Building audit tool..."
	mkdir -p bin
	go build -o bin/audit ./cmd/audit
	@echo "✓ Binary: ./bin/audit"

run: build
	@echo "Running audit..."
	@if [ ! -f inventory.json ]; then \
		echo "❌ inventory.json not found. Run: make inventory"; \
		exit 1; \
	fi
	./bin/audit

inventory:
	@echo "Collecting system inventory..."
	./scripts/collect-inventory.sh inventory.json
	@echo "✓ Inventory saved to inventory.json"

audit-full: inventory run
	@echo "✅ Audit complete!"
	@echo "  JSON: audit_report.json"
	@echo "  HTML: audit_report.html"

test:
	@echo "Running tests..."
	go test -v -race ./...

coverage:
	@echo "Running tests with coverage..."
	go test -v -race -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out -o coverage.html
	@echo "✓ Coverage report: coverage.html"
	@go tool cover -func=coverage.out | tail -1

lint:
	@echo "Running linters..."
	@which golangci-lint > /dev/null || (echo "Install with: make install-tools" && exit 1)
	golangci-lint run --timeout=5m ./...
	@echo "✓ Linting passed"

fmt:
	@echo "Formatting code..."
	go fmt ./...
	go vet ./...
	@echo "✓ Code formatted"

vulnerability:
	@echo "Checking for known vulnerabilities..."
	@which govulncheck > /dev/null || (echo "Install with: make install-tools" && exit 1)
	govulncheck ./...
	@echo "✓ No known vulnerabilities"

ci: fmt lint test vulnerability
	@echo "✅ All CI checks passed"

clean:
	@echo "Cleaning..."
	rm -rf bin dist coverage.out coverage.html
	rm -f inventory.json audit_report.json audit_report.html audit_data.json
	go clean

.DEFAULT_GOAL := help
