# Makefile for LMA code quality, building, and deployment
#
# Run 'make help' to see all available targets.

SHELL := /bin/bash

# Define color codes
RED := \033[0;31m
GREEN := \033[0;32m
YELLOW := \033[1;33m
CYAN := \033[0;36m
BOLD := \033[1m
NC := \033[0m  # No Color

# Virtual environment configuration
VENV_DIR := .venv
# Use the venv python/pip if the venv exists, otherwise fall back to system
ifeq ($(wildcard $(VENV_DIR)/bin/python),)
  PYTHON := $(shell command -v python3 2>/dev/null || echo python)
  PIP := $(shell command -v pip3 2>/dev/null || echo pip)
else
  PYTHON := $(CURDIR)/$(VENV_DIR)/bin/python
  PIP := $(CURDIR)/$(VENV_DIR)/bin/pip
endif
# setup-python installs cfn-lint into the venv, which is not on PATH in CI.
ifeq ($(wildcard $(VENV_DIR)/bin/cfn-lint),)
  CFN_LINT := cfn-lint
else
  CFN_LINT := $(CURDIR)/$(VENV_DIR)/bin/cfn-lint
endif
# Likewise ruff.
ifeq ($(wildcard $(VENV_DIR)/bin/ruff),)
  RUFF := ruff
else
  RUFF := $(CURDIR)/$(VENV_DIR)/bin/ruff
endif

# Project paths
AI_STACK_DIR := lma-ai-stack
UI_DIR := $(AI_STACK_DIR)/source/ui
LAMBDA_FUNCTIONS_DIR := $(AI_STACK_DIR)/source/lambda_functions
LAMBDA_LAYERS_DIR := $(AI_STACK_DIR)/source/lambda_layers
WEBSOCKET_DIR := lma-websocket-transcriber-stack
WEBSOCKET_APP_DIR := $(WEBSOCKET_DIR)/source/app
VP_DIR := lma-virtual-participant-stack
VP_BACKEND_DIR := $(VP_DIR)/backend
WEBSOCKET_CLIENT_DIR := utilities/websocket-client
ASR_DIR := lma-asr-microvm-stack
ASR_SOURCE_DIR := $(ASR_DIR)/source
LOAD_SIM_DIR := utilities/load-simulator
MEETINGASSIST_TEST_DIR := lma-meetingassist-setup-stack/test
# The Cognito stack's Lambda triggers (lma-cognito-stack/source/<trigger>/).
COGNITO_SOURCE_DIR := lma-cognito-stack/source
STRANDS_LAYER_REQUIREMENTS := lma-meetingassist-setup-stack/strands_layer/requirements.txt
VERSION_FILE := VERSION
PYTHON_LINE_LENGTH := 100
# The ruff version comes from the ASR runtime's pin, so the AI-stack lint and the
# ASR lint (`test-asr`) run the same ruff release. Each uses its own tree's
# configuration. Dependabot keeps that pin current.
RUFF_VERSION := $(shell sed -n 's/^ruff==//p' $(ASR_SOURCE_DIR)/requirements-dev.txt)
# Everything `lint-python` fixes and `lint-python-check` checks. The Lambda
# layers are included because their code is imported by most of the functions.
# The rest of scripts/ is not included: those files predate this and
# reformatting them here would make an unrelated diff. The parameter reference
# generator and the demo recorder (with its tests) were written to this lint, so
# they are named.
PYTHON_LINT_PATHS := \
	$(CURDIR)/$(LAMBDA_FUNCTIONS_DIR) \
	$(CURDIR)/$(LAMBDA_LAYERS_DIR) \
	$(CURDIR)/$(COGNITO_SOURCE_DIR) \
	$(CURDIR)/scripts/pr_review \
	$(CURDIR)/scripts/ci \
	$(CURDIR)/scripts/security \
	$(CURDIR)/scripts/cloudformation_parameters_doc.py \
	$(CURDIR)/scripts/bedrock_inference_catalog.py \
	$(CURDIR)/scripts/ux_recorder.py \
	$(CURDIR)/scripts/ux_recorder_cdp.py \
	$(CURDIR)/scripts/ux_recorder_render.py \
	$(CURDIR)/scripts/ux_test_session.py \
	$(CURDIR)/scripts/meeting_guest \
	$(CURDIR)/scripts/synthetic_meetings \
	$(CURDIR)/scripts/tests \
	$(CURDIR)/scripts/testing \
	$(CURDIR)/scripts/solution_profile \
	$(CURDIR)/lma-browser-extension-stack/e2e

# CloudFormation templates to validate
CFN_TEMPLATES := \
	lma-main.yaml \
	$(AI_STACK_DIR)/deployment/lma-ai-stack.yaml \
	$(AI_STACK_DIR)/deployment/lma-ai-lambda-resolvers.yaml \
	$(AI_STACK_DIR)/deployment/lma-ai-meeting-events.yaml \
	$(AI_STACK_DIR)/deployment/virtual-participant-enhancements.yaml \
	$(ASR_DIR)/template.yaml \
	lma-bedrockagent-stack/template.yaml \
	lma-bedrockkb-stack/template.yaml \
	lma-browser-extension-stack/template.yaml \
	lma-chat-button-config-stack/deployment/chat-button-config.yaml \
	lma-cognito-stack/deployment/lma-cognito-stack.yaml \
	lma-desktop-capture-app-stack/template.yaml \
	lma-llm-template-setup-stack/deployment/llm-template-setup.yaml \
	lma-meetingassist-setup-stack/template.yaml \
	lma-nova-sonic-config-stack/deployment/nova-sonic-config.yaml \
	$(VP_DIR)/template.yaml \
	lma-vpc-stack/template.yaml \
	$(WEBSOCKET_DIR)/deployment/lma-websocket-transcriber.yaml

# Discover Python Lambda function directories (those with .py files)
LAMBDA_FUNCTION_DIRS := $(sort $(dir $(wildcard $(LAMBDA_FUNCTIONS_DIR)/*/*.py)))

##@ General
.PHONY: help
help: ## Show this help message
	@echo ""
	@echo "Usage: make [target]"
	@echo ""
	@awk 'BEGIN {FS = ":.*##"; section=""} \
		/^##@/ { section=substr($$0, 5); next } \
		/^[a-zA-Z_-]+:.*?## / { \
			if (section != "" && section != last_section) { \
				printf "\n  \033[1m%s\033[0m\n", section; \
				last_section = section \
			}; \
			printf "  \033[36m%-25s\033[0m %s\n", $$1, $$2 \
		}' $(MAKEFILE_LIST)
	@echo ""

# Default target
.DEFAULT_GOAL := all
all: lint ## Run all linting (default)

# Node.js version pinned for development and CI. `.nvmrc` is the single source
# of truth: setup-node installs it via nvm, GitHub Actions reads it through
# `node-version-file`, and .gitlab-ci.yml downloads the same version.
NODE_PINNED_VERSION := $(strip $(shell cat .nvmrc 2>/dev/null))
# Minimum acceptable version, matching the `engines` field of the UI's
# package.json (jsdom 30 needs >= 22.22.2). Any Node at or above this works;
# check-node reports a shortfall in one line, since NPM_CI below runs npm
# quietly and its EBADENGINE warnings are therefore suppressed.
NODE_MIN_VERSION := 22.22.2

# When nvm has the pinned version installed, put it first on PATH for every
# recipe, so `make` uses it even in a shell that was opened before
# `make setup-node` changed the nvm default (astro in docs-site needs the
# pinned version, newer than NODE_MIN_VERSION). CI installs Node without nvm,
# so there this is empty and PATH is unchanged.
NVM_PINNED_NODE_BIN := $(wildcard $(or $(NVM_DIR),$(HOME)/.nvm)/versions/node/v$(NODE_PINNED_VERSION)/bin)
ifneq ($(NVM_PINNED_NODE_BIN),)
export PATH := $(NVM_PINNED_NODE_BIN):$(PATH)
endif

# npm install invocation shared by every JS target. `--loglevel=error --no-fund`
# drops npm's notice-level output (funding summaries, transitive `deprecated`
# notices, and peer-dependency/engine warnings for packages we do not control)
# while still surfacing real install failures.
NPM_CI := npm ci --prefer-offline --no-audit --no-fund --loglevel=error

##@ Setup
setup: setup-node setup-python setup-cli-dev ## Set up dev environment (Node version, Python venv, CLI)
	@echo ""
	@echo -e "$(GREEN)✅ Full setup complete!$(NC)"

setup-node: ## Install the Node.js version pinned in .nvmrc via nvm and make it the default
	@CURRENT=$$(node -v 2>/dev/null | sed 's/^v//'); \
	DEFAULT=$$(source "$$HOME/.nvm/nvm.sh" >/dev/null 2>&1 && nvm version default 2>/dev/null | sed 's/^v//'); \
	OK=0; \
	if [ -n "$$CURRENT" ] && \
	   [ "$$(printf '%s\n%s\n' "$(NODE_MIN_VERSION)" "$$CURRENT" | sort -V | head -n1)" = "$(NODE_MIN_VERSION)" ]; then \
		OK=1; \
	fi; \
	if [ $$OK -eq 1 ] && { [ -z "$$DEFAULT" ] || \
	   [ "$$(printf '%s\n%s\n' "$(NODE_MIN_VERSION)" "$$DEFAULT" | sort -V | head -n1)" = "$(NODE_MIN_VERSION)" ]; }; then \
		echo -e "$(GREEN)✅ Node.js v$$CURRENT already active$(NC)"; \
	elif [ -s "$$HOME/.nvm/nvm.sh" ]; then \
		if [ $$OK -eq 1 ]; then \
			echo "Node.js v$$CURRENT is current, but the nvm default is v$$DEFAULT (new shells would use it)."; \
		else \
			echo "Current Node.js: v$${CURRENT:-not found} (need v$(NODE_MIN_VERSION) or later)"; \
		fi; \
		echo "Using nvm to install Node $(NODE_PINNED_VERSION) (pinned in .nvmrc)..."; \
		source "$$HOME/.nvm/nvm.sh" && \
			nvm install $(NODE_PINNED_VERSION) && \
			nvm use $(NODE_PINNED_VERSION) && \
			nvm alias default $(NODE_PINNED_VERSION); \
		echo -e "$(GREEN)✅ Node.js $(NODE_PINNED_VERSION) installed and set as the nvm default$(NC)"; \
		echo -e "$(YELLOW)   This shell still has v$${CURRENT:-none} — run 'nvm use' here, or open a new shell$(NC)"; \
	else \
		echo -e "$(RED)ERROR: Node.js v$(NODE_MIN_VERSION) or later is required but v$${CURRENT:-none} is active.$(NC)"; \
		echo -e "$(YELLOW)   Install nvm: https://github.com/nvm-sh/nvm$(NC)"; \
		echo -e "$(YELLOW)   Then run: nvm install && nvm use   (both read .nvmrc)$(NC)"; \
		exit 1; \
	fi

setup-python: ## Create .venv and install Python dev/lint dependencies
	@if [ ! -f "$(VENV_DIR)/bin/python" ]; then \
		echo "Creating virtual environment in $(VENV_DIR)..."; \
		PYENV_PYTHON=$$(pyenv which python 2>/dev/null); \
		SYS_PYTHON=$$(command -v python3 2>/dev/null); \
		BASE_PYTHON=$${PYENV_PYTHON:-$$SYS_PYTHON}; \
		if [ -z "$$BASE_PYTHON" ]; then \
			echo -e "$(RED)ERROR: No python3 or pyenv python found. Install Python 3+ first.$(NC)"; \
			exit 1; \
		fi; \
		echo "Using base Python: $$BASE_PYTHON ($$($$BASE_PYTHON --version))"; \
		$$BASE_PYTHON -m venv $(VENV_DIR); \
	else \
		echo "Virtual environment already exists at $(VENV_DIR)"; \
	fi
	@echo "Upgrading pip..."
	$(VENV_DIR)/bin/pip install --upgrade pip
	@echo "Installing Python lint/dev tools..."
# aws-sam-translator: lma-ai-stack/test/test_resource_budget.py runs the SAM
# transform to count the AI stack's resources. cfn-lint no longer installs it.
# jsonschema: meeting_archive/test_export.py validates the meeting export against
# docs/schemas/meeting-export-v1.schema.json; listed here so that test does not
# depend on the SDK's dev extras bringing it in.
# pyyaml and jsonschema are pinned to the versions the vendored solution profile
# validator declares (solution-profile/schema/v1/validate_profile.py), which the
# release workflow installs, so a passing `make solution-profile-check` predicts
# the release build; test_solution_profile.py holds the three to the same pins.
# Both satisfy cfn-lint (pyyaml>=6.0.3) and aws-sam-translator (jsonschema>=4.23,<5).
	@test -n "$(RUFF_VERSION)" || { echo -e "$(RED)ERROR: no ruff==<version> pin in $(ASR_SOURCE_DIR)/requirements-dev.txt, which is where RUFF_VERSION is read from.$(NC)"; exit 1; }
	$(VENV_DIR)/bin/pip install \
		aws-sam-translator \
		bandit \
		black \
		cfn-lint \
		flake8 \
		jsonschema==4.25.1 \
		mypy \
		pylint \
		pyyaml==6.0.3 \
		ruff==$(RUFF_VERSION) \
		virtualenv \
		yamllint \
		boto3-stubs[comprehend,codebuild,dynamodb,lambda,lexv2-runtime,s3,sqs,sns]
	@echo ""
	@echo -e "$(GREEN)✅ Python setup complete! Virtual environment at $(VENV_DIR)$(NC)"
	@echo -e "$(YELLOW)   All 'make' targets will automatically use $(VENV_DIR)/bin/python.$(NC)"
	@echo -e "$(YELLOW)   To activate manually: source $(VENV_DIR)/bin/activate$(NC)"

setup-cli: ## Install LMA SDK and CLI packages into current Python environment
	@echo "Installing LMA SDK..."
	$(CURDIR)/$(VENV_DIR)/bin/pip install -e lib/lma_sdk
	@echo "Installing LMA CLI..."
	$(CURDIR)/$(VENV_DIR)/bin/pip install -e lib/lma_cli_pkg
	@echo -e "$(GREEN)✅ LMA SDK and CLI installed! Run 'lma --help' to get started.$(NC)"

setup-cli-dev: ## Install LMA SDK and CLI with dev/test dependencies
	@echo "Installing LMA SDK with dev dependencies..."
	$(CURDIR)/$(VENV_DIR)/bin/pip install -e "lib/lma_sdk[dev]"
	@echo "Installing LMA CLI with dev dependencies..."
	$(CURDIR)/$(VENV_DIR)/bin/pip install -e "lib/lma_cli_pkg[dev]"
	@# The troubleshooting agent's budget is tested through the real Strands event
	@# loop (lma-meetingassist-setup-stack/test/test_troubleshooting_real_strands.py),
	@# which skips without it. The version is read from the layer's own pin so the
	@# tests cannot drift from what is deployed.
	@echo "Installing the Strands Agents SDK at the version the Strands layer pins..."
	$(CURDIR)/$(VENV_DIR)/bin/pip install "$$(grep -E '^strands-agents==' $(STRANDS_LAYER_REQUIREMENTS))"
	@# The voice-enrollment client's tests run an embedding session against a
	@# local WebSocket server, and skip without the library. Installs the same
	@# requirement line as the function (a minimum version, not a pin).
	@echo "Installing websockets to the voice-enrollment function's requirement..."
	$(CURDIR)/$(VENV_DIR)/bin/pip install "$$(grep -E '^websockets' $(LAMBDA_FUNCTIONS_DIR)/voice_enrollment_manager/requirements.txt)"
	@echo -e "$(GREEN)✅ LMA SDK and CLI (with test deps) installed!$(NC)"

.PHONY: check-node
check-node: ## Warn (one line) if the active Node.js is older than NODE_MIN_VERSION
	@CURRENT=$$(node -v 2>/dev/null | sed 's/^v//'); \
	if [ -z "$$CURRENT" ]; then \
		echo -e "$(RED)Node.js not found on PATH (need >= $(NODE_MIN_VERSION))$(NC)"; \
	elif [ "$$(printf '%s\n%s\n' "$(NODE_MIN_VERSION)" "$$CURRENT" | sort -V | head -n1)" != "$(NODE_MIN_VERSION)" ]; then \
		echo -e "$(YELLOW)Node.js v$$CURRENT is older than the required v$(NODE_MIN_VERSION) — run 'nvm use' (or 'make setup-node')$(NC)"; \
	fi

setup-npm: check-node ## Install npm dependencies for UI, WebSocket, and Virtual Participant
	@echo "Installing UI npm dependencies..."
	cd $(UI_DIR) && $(NPM_CI)
	@echo ""
	@echo "Installing WebSocket transcriber npm dependencies..."
	cd $(WEBSOCKET_APP_DIR) && $(NPM_CI)
	@echo ""
	@echo "Installing Virtual Participant npm dependencies..."
	cd $(VP_BACKEND_DIR) && $(NPM_CI)
	@echo ""
	@echo -e "$(GREEN)✅ npm dependencies installed!$(NC)"

##@ Code Quality
lint: lint-cfn lint-python lint-ui ## Run all linting (cfn, python, UI)
fastlint: lint-cfn lint-python ## Quick lint (skip UI checks)

lint-cfn: ## Validate CloudFormation templates with cfn-lint
	@echo "Running cfn-lint on CloudFormation templates..."
	@FAILED=0; \
	for template in $(CFN_TEMPLATES); do \
		if [ -f "$$template" ]; then \
			echo "  Checking $$template..."; \
			if ! $(CFN_LINT) --non-zero-exit-code error "$$template" > /dev/null 2>&1; then \
				echo -e "$(RED)  FAIL: $$template$(NC)"; \
				$(CFN_LINT) --non-zero-exit-code error "$$template"; \
				FAILED=1; \
			fi; \
		else \
			echo -e "$(YELLOW)  SKIP: $$template (not found)$(NC)"; \
		fi; \
	done; \
	if [ $$FAILED -eq 0 ]; then \
		echo -e "$(GREEN)✅ All CloudFormation templates passed cfn-lint!$(NC)"; \
	else \
		echo -e "$(RED)❌ Some CloudFormation templates have cfn-lint errors$(NC)"; \
		exit 1; \
	fi

# Runs from AI_STACK_DIR so that lma-ai-stack/pyproject.toml supplies the ruff
# configuration. lint-python rewrites files in place; lint-python-check is the
# read-only form that CI runs, and covers exactly the same paths.
lint-python: ## Lint and format Python Lambda functions and layers with ruff (fixes in place)
	@echo "Running ruff on Lambda functions and layers..."
	cd $(AI_STACK_DIR) && $(RUFF) check --fix $(PYTHON_LINT_PATHS)
	cd $(AI_STACK_DIR) && $(RUFF) format $(PYTHON_LINT_PATHS)
	@echo -e "$(GREEN)✅ All Python linting passed!$(NC)"

lint-python-check: ## Check Python Lambda functions and layers with ruff (no modifications)
	@echo "Checking Lambda functions and layers with ruff..."
	@if ! (cd $(AI_STACK_DIR) && $(RUFF) check $(PYTHON_LINT_PATHS)); then \
		echo -e "$(RED)ERROR: Ruff linting failed!$(NC)"; \
		echo -e "$(YELLOW)Run 'make lint-python' locally to fix these issues.$(NC)"; \
		exit 1; \
	fi
	@if ! (cd $(AI_STACK_DIR) && $(RUFF) format --check $(PYTHON_LINT_PATHS)); then \
		echo -e "$(RED)ERROR: Code formatting check failed!$(NC)"; \
		echo -e "$(YELLOW)Run 'make lint-python' locally to fix these issues.$(NC)"; \
		exit 1; \
	fi
	@echo -e "$(GREEN)✅ Ruff checks passed!$(NC)"

lint-bandit: ## Run bandit security scan on Python Lambda functions
	@echo "Running bandit security scan..."
	bandit --recursive $(LAMBDA_FUNCTIONS_DIR)
	@echo -e "$(GREEN)✅ Bandit security scan passed!$(NC)"

lint-mypy: ## Run mypy type checking on Python Lambda functions
	@echo "Running mypy type checks..."
	mypy --config-file $(AI_STACK_DIR)/mypy.ini $(LAMBDA_FUNCTIONS_DIR)
	@echo -e "$(GREEN)✅ mypy type checks passed!$(NC)"

# Checksum file for UI lint change detection
UI_LINT_CHECKSUM_FILE := .ui-lint-checksum

lint-ui: check-node ## Lint React UI (ESLint, skips if source unchanged; use FORCE=1 to bypass cache)
	@NEW_CHECKSUM=$$(find $(UI_DIR)/src -type f \( -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' \) 2>/dev/null | sort | xargs cat 2>/dev/null | sha256sum | awk '{print $$1}'); \
	OLD_CHECKSUM=$$(cat $(UI_LINT_CHECKSUM_FILE) 2>/dev/null || echo ""); \
	if [ -z "$(FORCE)" ] && [ "$$NEW_CHECKSUM" = "$$OLD_CHECKSUM" ]; then \
		echo -e "$(GREEN)✅ UI lint skipped — source unchanged since last run (use FORCE=1 to override)$(NC)"; \
	else \
		if [ -n "$(FORCE)" ]; then echo "Running UI lint (forced)..."; else echo "Running UI lint..."; fi; \
		cd $(UI_DIR) && $(NPM_CI) && npm run lint && \
		echo "$$NEW_CHECKSUM" > $(CURDIR)/$(UI_LINT_CHECKSUM_FILE) && \
		echo -e "$(GREEN)✅ UI lint passed!$(NC)"; \
	fi

lint-ui-force: ## Lint React UI (ignore checksum, always run)
	@$(MAKE) lint-ui FORCE=1

lint-typescript: ## TypeScript build check on WebSocket, Virtual Participant and websocket-client
	@echo "Running TypeScript build check on WebSocket transcriber..."
	@cd $(WEBSOCKET_APP_DIR) && $(NPM_CI) && npm run build
	@echo "Running TypeScript build check on Virtual Participant..."
	@cd $(VP_BACKEND_DIR) && $(NPM_CI) && npm run build
	@echo "Running TypeScript build check on utilities/websocket-client..."
	@cd $(WEBSOCKET_CLIENT_DIR) && $(NPM_CI) && npm run buildcheck
	@echo -e "$(GREEN)✅ All TypeScript builds succeeded!$(NC)"

format: ## Format Python code with ruff
	@echo "Formatting Python Lambda functions and layers with ruff..."
	cd $(AI_STACK_DIR) && $(RUFF) format $(PYTHON_LINT_PATHS)
	@echo -e "$(GREEN)✅ Python code formatted!$(NC)"

lint-cicd: ## CI/CD lint — checks only, no modifications
	@echo "Running code quality checks (CI/CD mode — no auto-fix)..."
	@if ! $(CFN_LINT) --non-zero-exit-code error $(AI_STACK_DIR)/deployment/lma-ai-stack.yaml; then \
		echo -e "$(RED)ERROR: cfn-lint failed!$(NC)"; \
		exit 1; \
	fi
	@$(MAKE) --no-print-directory lint-python-check
	@if ! make lint-ui; then \
		echo -e "$(RED)ERROR: UI lint failed$(NC)"; \
		exit 1; \
	fi
	@echo -e "$(GREEN)All code quality checks passed!$(NC)"

##@ Building
build: build-ui build-websocket build-vp ## Build all stacks

build-ui: check-node ## Build React UI for production
	@echo "Building React UI..."
	cd $(UI_DIR) && $(NPM_CI) && npm run build
	@echo -e "$(GREEN)✅ UI build complete!$(NC)"

build-websocket: ## Build WebSocket transcriber (TypeScript)
	@echo "Building WebSocket transcriber..."
	cd $(WEBSOCKET_APP_DIR) && $(NPM_CI) && npm run build
	@echo -e "$(GREEN)✅ WebSocket transcriber build complete!$(NC)"

build-vp: ## Build Virtual Participant (TypeScript)
	@echo "Building Virtual Participant..."
	cd $(VP_BACKEND_DIR) && $(NPM_CI) && npm run build
	@echo -e "$(GREEN)✅ Virtual Participant build complete!$(NC)"

##@ Testing
test: test-ui test-sdk test-cli test-lambdas test-ai-stack test-integ-plumbing test-asr test-load-simulator test-pr-review test-ux-recorder test-ci-tooling test-solution-profile ## Run all tests (no AWS required)

test-sdk: ## Run LMA SDK unit tests
	@echo "Running LMA SDK tests..."
	cd lib/lma_sdk && $(PYTHON) -m pytest tests/ -v
	@echo -e "$(GREEN)✅ LMA SDK tests passed!$(NC)"

test-cli: ## Run LMA CLI unit tests
	@echo "Running LMA CLI tests..."
	cd lib/lma_cli_pkg && $(PYTHON) -m pytest tests/ -v
	@echo -e "$(GREEN)✅ LMA CLI tests passed!$(NC)"

# Lambda unit tests live next to each function's source and use local (sibling)
# imports, so each directory must be run with that dir on sys.path — a single
# top-level `pytest lambda_functions/` collides on duplicate module names. This
# target discovers every dir containing test_*.py and runs pytest from within
# it. No AWS required (the suites mock boto3 / set dummy env), and none reached:
# lma-ai-stack/conftest.py, the ASR Lambdas' and the meeting-assist tests'
# conftest.py load scripts/testing/no_real_aws.py, which fails a test that sends
# a request to AWS.
#
# LAMBDA_LAYERS_DIR is searched too. The layer holds the code the Lambdas share
# (transcript normalisation, the TTLs, the AppSync helpers), so a test there
# covers every function at once; it was previously outside this glob, which meant
# a test placed beside the layer would have been collected by nothing.
#
# MEETINGASSIST_TEST_DIR is searched for the same reason: it holds the tests
# for the troubleshooting agent, which nothing else would collect.
# Unusually for this repository those tests are NOT beside their source, and
# that is deliberate — three functions in that stack share one `Code: ./src`,
# so a test file there would ship in all three deployment packages and editing
# a test would change the meeting-assist function's code hash. A conftest.py
# in the test directory restores the sibling imports.
#
# -rs lists the skips. Several suites skip themselves when a runtime dependency
# is absent, which is right for a developer who has run only `make setup-python`
# and wrong to pass silently in CI, where `make setup-cli-dev` installs them: a
# suite that has quietly stopped running shows up in this output.
test-lambdas: ## Run all Lambda function + layer unit tests (no AWS; each dir isolated)
	@echo "Running Lambda function unit tests..."
	@FAILED=0; RAN=0; \
	for d in $$(find $(LAMBDA_FUNCTIONS_DIR) $(LAMBDA_LAYERS_DIR) $(ASR_DIR)/lambda_functions $(MEETINGASSIST_TEST_DIR) $(COGNITO_SOURCE_DIR) -name 'test_*.py' -not -path '*/node_modules/*' -exec dirname {} \; | sort -u); do \
		files=$$(cd "$$d" && ls test_*.py 2>/dev/null); \
		[ -z "$$files" ] && continue; \
		RAN=$$((RAN+1)); \
		echo -e "$(CYAN)  pytest $$d$(NC)"; \
		if ! ( cd "$$d" && AWS_DEFAULT_REGION=$${AWS_DEFAULT_REGION:-us-east-1} \
			AWS_REGION=$${AWS_REGION:-us-east-1} \
			$(PYTHON) -m pytest -q -rs $$files ); then FAILED=1; fi; \
	done; \
	if [ $$RAN -eq 0 ]; then echo -e "$(YELLOW)  no lambda tests found$(NC)"; fi; \
	if [ $$FAILED -ne 0 ]; then echo -e "$(RED)❌ Some Lambda tests failed$(NC)"; exit 1; fi; \
	echo -e "$(GREEN)✅ Lambda function tests passed!$(NC)"

# Checksum file for UI test change detection
UI_TEST_CHECKSUM_FILE := .ui-test-checksum

test-ui: check-node ## Run React UI tests (skips if source unchanged)
	@NEW_CHECKSUM=$$(find $(UI_DIR)/src $(UI_DIR)/public -type f \( -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.json' -o -name '*.html' \) 2>/dev/null | sort | xargs cat 2>/dev/null | sha256sum | awk '{print $$1}'); \
	OLD_CHECKSUM=$$(cat $(UI_TEST_CHECKSUM_FILE) 2>/dev/null || echo ""); \
	if [ "$$NEW_CHECKSUM" = "$$OLD_CHECKSUM" ]; then \
		echo -e "$(GREEN)✅ UI tests skipped — source unchanged since last run$(NC)"; \
	else \
		echo "Running UI tests..."; \
		cd $(UI_DIR) && $(NPM_CI) && CI=true npm test -- --run && \
		echo "$$NEW_CHECKSUM" > $(CURDIR)/$(UI_TEST_CHECKSUM_FILE) && \
		echo -e "$(GREEN)✅ UI tests passed!$(NC)"; \
	fi

test-vp: ## Run Virtual Participant backend unit tests (no AWS)
	@echo "Running Virtual Participant backend unit tests..."
	cd $(VP_BACKEND_DIR) && $(NPM_CI) && npm test
	@echo -e "$(GREEN)✅ Virtual Participant unit tests passed!$(NC)"

# Collects the whole directory rather than naming each file: the list used to be
# spelled out here and a new test file only ran in CI if its author remembered to
# append it, which twice they did not. Everything in that directory is a static
# test needing no AWS, and the one module that is not a test suite
# (validate_state_machine.py, a helper) is not named test_* so pytest skips it.
test-vp-template: ## Static tests on the VP template + MicroVM client (no AWS)
	@echo "Running Virtual Participant template + MicroVM client tests..."
	$(PYTHON) -m pytest $(VP_DIR)/test/ -q
	@echo -e "$(GREEN)✅ Virtual Participant template tests passed!$(NC)"

# One target for every static AI stack test, collecting the directory rather than
# naming files: the AppSync schema/resolver/UI-operation contract and the
# CloudFormation template's invariants both live in $(AI_STACK_DIR)/test/, and a
# test added there should run in CI without anyone having to remember to name it
# (the same reason test-vp-template collects its directory).
test-ai-stack: ## Static AppSync contract + AI stack template tests (no AWS)
	@echo "Running AI stack static tests..."
	$(PYTHON) -m pytest $(AI_STACK_DIR)/test/ -q
	@echo -e "$(GREEN)✅ AI stack static tests passed!$(NC)"

# Everything else under integ-tests/ needs a deployed stack. This one file does
# not, and it runs in the fast pipeline because it covers the machinery that
# decides whether a scheduled integration run can report success without having
# tested anything — credential resolution and the --no-skips hook.
test-integ-plumbing: ## Unit tests for the scheduled integ-test machinery and the security test tooling (no AWS)
	@echo "Running integration-test plumbing unit tests..."
	$(PYTHON) -m pytest integ-tests/test_ci_plumbing.py integ-tests/test_security_helpers.py integ-tests/test_config_readers.py -q
	$(PYTHON) -m pytest scripts/security/tests -q
	@echo -e "$(GREEN)✅ Integration-test plumbing tests passed!$(NC)"

# The advisory AI review's own machinery. The disclosure guard is the part that
# matters: it decides whether a model-written comment describing a security
# weakness reaches a public pull request, so both of its failure directions are
# covered — a miss (publishes a weakness, nobody finds out) and a false positive
# (withholds a legitimate review, which is how a guard gets deleted). The rest
# pins the four workflow properties an edit removes without noticing.
test-pr-review: ## Unit tests for the advisory AI review harness (no AWS, no model call)
	@echo "Running advisory AI review tests..."
	$(PYTHON) -m pytest scripts/pr_review/test_ai_pr_review.py -q
	@echo -e "$(GREEN)✅ Advisory AI review tests passed!$(NC)"

# The solution profile (solution-profile/, docs/solution-profile.md): the vendored
# reference validator, run with the contract form of VERSION, then cross-checks
# that fail when the code gains an MCP tool, Virtual Participant platform,
# configuration preset or release Region the profile does not cover. The release
# rules (reviewed_for_version == version, a changes.yaml entry for it) apply when
# VERSION is a final X.Y.Z, or with SOLUTION_PROFILE_RELEASE=1.
solution-profile-check: ## Validate solution-profile/ against its contract and cross-check it with the code (no AWS)
	@$(PYTHON) scripts/solution_profile/check.py || \
		(echo -e "$(RED)ERROR: the solution profile is invalid or behind the code (see docs/solution-profile.md)$(NC)" && exit 1)

test-solution-profile: ## Unit tests for the solution profile check and its deterministic release build (no AWS)
	@echo "Running solution profile tests..."
	$(PYTHON) -m pytest scripts/solution_profile -q
	@echo -e "$(GREEN)✅ Solution profile tests passed!$(NC)"

# The release asset. Not a gate: .github/workflows/solution-profile-release.yml
# builds it when a GitHub Release is published, and test-solution-profile proves
# two builds byte-identical.
solution-profile-build: ## Build the solution-profile release tarball, .sha256 and .build.json into dist/ (TAG=v<x.y.z> optional)
	@$(PYTHON) scripts/solution_profile/build.py --out-dir dist --validate $(if $(TAG),--tag $(TAG),)

# The CI step selection (scripts/ci/changed_areas.py): which steps of the "Lint and
# unit tests" job a pull request's changed files need, plus the check that every
# gated step in code-checks.yml and .gitlab-ci.yml names a real selection key.
test-ci-tooling: ## Unit tests for the CI step selection (scripts/ci; no AWS)
	@echo "Running CI step-selection tests..."
	$(PYTHON) -m pytest scripts/ci -q
	@echo -e "$(GREEN)✅ CI step-selection tests passed!$(NC)"

# The built browser extension loaded into headless Chromium with Playwright
# (lma-browser-extension-stack/e2e). Needs `npm run build` in the extension first.
# Downloads Playwright's Chromium on first use (~170 MB, cached under
# ~/.cache/ms-playwright); CI passes PLAYWRIGHT_DEPS=--with-deps to install the
# system libraries it needs as well. No AWS, and nothing reaches the network.
# Not part of `make test`, which needs neither a build nor a browser.
PLAYWRIGHT_DEPS ?=
test-browser-extension-e2e: ## Load the built browser extension in headless Chromium (needs the extension build; no AWS)
	@echo "Running browser extension Playwright smoke tests..."
	$(PIP) install -q -r lma-browser-extension-stack/e2e/requirements.txt
	$(PYTHON) -m playwright install $(PLAYWRIGHT_DEPS) --no-shell chromium
	$(PYTHON) -m pytest lma-browser-extension-stack/e2e -q
	@echo -e "$(GREEN)✅ Browser extension smoke tests passed!$(NC)"

# The demo recorder (scripts/ux_recorder*.py), the stack-session helper and the
# product-demo skill's storyboard file. Needs no AWS, Chrome or network; the
# render tests skip without ffmpeg and Pillow.
test-ux-recorder: ## Unit tests for the product demo recorder, its session helper and the meeting guest (no AWS)
	@echo "Running demo recorder tests..."
	$(PYTHON) -m pytest scripts/tests -q
	@echo -e "$(GREEN)✅ Demo recorder tests passed!$(NC)"

# Run one review locally and PRINT it rather than posting. Usage:
#   make ai-pr-review PR=800
#   make ai-pr-review PR=800 ARGS=--no-redact-artifact   # keep withheld text locally
# Needs a `claude` CLI on PATH and AWS credentials with bedrock:InvokeModel. This
# is a real Bedrock spend (~$1-4); see scripts/pr_review/README.md.
#
# `--remote github` because a developer checkout of this repository has two
# remotes and `origin` is the GitLab mirror, which carries no refs/pull/* refs.
ai-pr-review: ## Dry-run the advisory AI review on one PR, printed not posted (Usage: make ai-pr-review PR=<n>)
	@if [ -z "$(PR)" ]; then \
		echo -e "$(RED)Usage: make ai-pr-review PR=<number>$(NC)"; exit 1; \
	fi
	$(PYTHON) scripts/pr_review/ai_pr_review.py \
		--forge github --remote github --mr $(PR) --dry-run $(ARGS)

test-asr: ## Run ASR MicroVM runtime unit tests (no AWS, no model weights)
	@echo "Running ASR MicroVM runtime tests..."
	@test -d $(ASR_SOURCE_DIR)/.venv || $(PYTHON) -m venv $(ASR_SOURCE_DIR)/.venv
	@$(ASR_SOURCE_DIR)/.venv/bin/pip install -q -r $(ASR_SOURCE_DIR)/requirements-dev.txt
	cd $(ASR_SOURCE_DIR) && .venv/bin/python -m pytest -q && .venv/bin/ruff check .
	$(ASR_SOURCE_DIR)/.venv/bin/python $(ASR_DIR)/scripts/sync_bundles.py --check
	@echo -e "$(GREEN)✅ ASR MicroVM runtime tests passed!$(NC)"

test-load-simulator: ## Run load simulator unit tests, including the ASR benchmark (no AWS)
	@echo "Running load simulator tests..."
	@test -d $(LOAD_SIM_DIR)/.venv || $(PYTHON) -m venv $(LOAD_SIM_DIR)/.venv
	@$(LOAD_SIM_DIR)/.venv/bin/pip install -q -e lib/lma_sdk -e "$(LOAD_SIM_DIR)[dev]"
	cd $(LOAD_SIM_DIR) && .venv/bin/python -m pytest -q tests
	@echo -e "$(GREEN)✅ Load simulator tests passed!$(NC)"

test-ui-force: check-node ## Run React UI tests (ignore checksum, always run)
	@echo "Running UI tests (forced)..."
	cd $(UI_DIR) && $(NPM_CI) && CI=true npm test -- --run
	@find $(UI_DIR)/src $(UI_DIR)/public -type f \( -name '*.js' -o -name '*.jsx' -o -name '*.ts' -o -name '*.tsx' -o -name '*.css' -o -name '*.json' -o -name '*.html' \) 2>/dev/null | sort | xargs cat 2>/dev/null | sha256sum | awk '{print $$1}' > $(UI_TEST_CHECKSUM_FILE)
	@echo -e "$(GREEN)✅ UI tests passed!$(NC)"

##@ Coverage
# Measurement only. There is deliberately no threshold and this cannot fail a
# build: the point of the first step is a baseline a threshold can be argued
# from. scripts/coverage_report.py explains how the numbers are arrived at, and
# in particular how source files that no test imports are accounted for rather
# than dropped from the denominator.
#
# Slower than `make test` — it runs every suite, and the Node ones compile first.
test-coverage: check-node ## Measure line coverage for every suite and print a table (no AWS)
	@echo "Measuring coverage across all components..."
	@test -d $(ASR_SOURCE_DIR)/.venv || $(PYTHON) -m venv $(ASR_SOURCE_DIR)/.venv
	@$(ASR_SOURCE_DIR)/.venv/bin/pip install -q -r $(ASR_SOURCE_DIR)/requirements-dev.txt
	@cd $(VP_BACKEND_DIR) && $(NPM_CI)
	@cd $(WEBSOCKET_APP_DIR) && $(NPM_CI)
	@cd $(UI_DIR) && $(NPM_CI)
	$(PYTHON) scripts/coverage_report.py $(if $(JSON),--json $(JSON),)

test-coverage-python: ## Coverage for the Python suites only (faster; no npm)
	@test -d $(ASR_SOURCE_DIR)/.venv || $(PYTHON) -m venv $(ASR_SOURCE_DIR)/.venv
	@$(ASR_SOURCE_DIR)/.venv/bin/pip install -q -r $(ASR_SOURCE_DIR)/requirements-dev.txt
	$(PYTHON) scripts/coverage_report.py --only "LMA SDK" --only "LMA CLI" \
		--only "Lambda" --only "ASR"

##@ Docker Build Checks
# These target names collide with real paths (e.g. the integ-tests/ dir), so
# declare them PHONY or make treats them as up-to-date files and skips them.
.PHONY: docker-build-check docker-build-check-transcriber docker-build-check-vp \
        docker-build-check-all integ-tests integ-tests-live integ-tests-nightly \
        integ-deploy-and-test test-lambdas \
        test-vp test-vp-template test-vp-microvm-e2e test-ai-stack \
        test-integ-plumbing test-coverage test-coverage-python test-asr \
        test-pr-review ai-pr-review test-browser-extension-e2e
# Build the container images the SAME way the in-stack CodeBuild projects do,
# locally, to catch Dockerfile / build-context regressions (e.g. a COPY of a
# renamed/deleted file) in ~1-2 min instead of via a ~40-min deploy that then
# rolls back. The transcriber image runs 'tsc && eslint' at build time, so this
# also catches missing lint/build config. Requires a running Docker daemon.
# A failed image build fails the target. Only removing the throwaway tag
# afterwards is allowed to fail. A missing docker CLI or a stopped daemon is
# reported as an error rather than skipped, because a check that skips quietly
# reads the same as one that passed.
DOCKER_BUILD_CHECK_PREFLIGHT = command -v docker >/dev/null 2>&1 \
	|| { echo -e "$(RED)ERROR: docker CLI not found; docker-build-check needs Docker.$(NC)"; exit 1; }; \
	docker info >/dev/null 2>&1 \
	|| { echo -e "$(RED)ERROR: Docker daemon not reachable (is it running?); docker-build-check needs it.$(NC)"; exit 1; }

docker-build-check: docker-build-check-transcriber ## Build container images locally as CodeBuild does (transcriber; use docker-build-check-all for VP too)
	@echo -e "$(GREEN)✅ Docker build check passed!$(NC)"

docker-build-check-transcriber: ## Build the WebSocket transcriber image (fast; runs tsc + eslint 10)
	@$(DOCKER_BUILD_CHECK_PREFLIGHT)
	@echo -e "$(CYAN)Building transcriber image (source/app/)...$(NC)"
	@cd $(WEBSOCKET_APP_DIR) && docker build --pull -t lma-transcriber-buildcheck:local .
	@docker rmi lma-transcriber-buildcheck:local >/dev/null 2>&1 || true
	@echo -e "$(GREEN)✅ Transcriber image built.$(NC)"

docker-build-check-vp: ## Build the Virtual Participant image (heavy; downloads CloakBrowser Chromium)
	@$(DOCKER_BUILD_CHECK_PREFLIGHT)
	@echo -e "$(CYAN)Building Virtual Participant image (backend/) — this is heavy...$(NC)"
	@cd $(VP_BACKEND_DIR) && docker build --pull -t lma-vp-buildcheck:local .
	@docker rmi lma-vp-buildcheck:local >/dev/null 2>&1 || true
	@echo -e "$(GREEN)✅ Virtual Participant image built.$(NC)"

docker-build-check-all: docker-build-check-transcriber docker-build-check-vp ## Build BOTH container images locally
	@echo -e "$(GREEN)✅ All Docker build checks passed!$(NC)"

# Container-level e2e for the MicroVM launch path. Needs no AWS: it drives the
# Lambda MicroVMs lifecycle hooks against a locally-run container and asserts
# the things unit tests can't reach — that the pre-snapshot stack really comes
# up (Xvfb/x11vnc/websockify/PulseAudio 3-sink topology), that /ready gates the
# snapshot on health, that /run injects per-meeting config into a real app
# process, that ALB self-registration is skipped, and that secrets stay out of
# logs. Builds the image on first run (heavy), reuses it afterwards.
test-vp-microvm-e2e: ## VP MicroVM launch-path e2e against a local container (no AWS; builds image if absent)
	@command -v docker >/dev/null 2>&1 || { echo -e "$(RED)ERROR: docker not found / daemon not running.$(NC)"; exit 1; }
	@echo -e "$(CYAN)Running VP MicroVM launch-path e2e...$(NC)"
	@bash $(VP_BACKEND_DIR)/test/microvm-e2e.sh lma-vp-microvm-e2e
	@echo -e "$(GREEN)✅ VP MicroVM e2e passed!$(NC)"

##@ Integration Testing
# End-to-end tests against a LIVE deployed stack (see integ-tests/README.md and
# the 'integ-tests' Claude skill). Requires the LMA SDK installed in the venv
# (make setup-cli-dev) and AWS creds (AWS_PROFILE=default). Resolves the target
# stack from STACK, else $LMA_STACK_NAME, else 'LMA'.
INTEG_STACK ?= $(or $(STACK),$(LMA_STACK_NAME),LMA)

asr-benchmark: ## Compare ASR model configurations on a live dev stack (Usage: make asr-benchmark STACK=<name> DATASET=ami/IS1009c|WAV=<stereo.wav> [BUNDLES=<a,b>] [TRANSCRIBE=1] [REFERENCE=<stm>] [KEEP_BUNDLE=1] [DRY_RUN=1], or STACK=<name> SWITCH_ONLY=<bundle>)
ifeq ($(STACK),)
	$(error Set STACK to the dev stack to benchmark: this target updates that stack's ASR bundle)
endif
ifeq ($(WAV)$(DATASET)$(SWITCH_ONLY),)
	$(error Set DATASET (e.g. ami/IS1009c) or WAV. Usage: make asr-benchmark STACK=<name> DATASET=ami/IS1009c BUNDLES=<a,b> [TRANSCRIBE=1])
endif
	@test -d $(LOAD_SIM_DIR)/.venv || $(PYTHON) -m venv $(LOAD_SIM_DIR)/.venv
	@$(LOAD_SIM_DIR)/.venv/bin/python -c "import lma_load, numpy" 2>/dev/null || $(LOAD_SIM_DIR)/.venv/bin/pip install -q -e lib/lma_sdk -e "$(LOAD_SIM_DIR)[benchmark]"
	$(LOAD_SIM_DIR)/.venv/bin/python -m lma_load.cli asr-benchmark --stack-name "$(STACK)" \
		$(if $(SWITCH_ONLY),--switch-only "$(SWITCH_ONLY)",$(if $(DATASET),--dataset "$(DATASET)",--wav "$(WAV)")) \
		$(if $(BUNDLES),--bundles "$(BUNDLES)") $(if $(TRANSCRIBE),--transcribe) \
		$(if $(REFERENCE),--reference "$(REFERENCE)") $(if $(KEEP_BUNDLE),--keep-bundle) \
		$(if $(DRY_RUN),--dry-run)

integ-tests: ## Run integration tests vs a live stack (Usage: make integ-tests STACK=<name>)
	@echo -e "$(CYAN)Running LMA integration tests against stack '$(INTEG_STACK)'...$(NC)"
	@if [ ! -x "$(VENV_DIR)/bin/pytest" ] && ! $(PYTHON) -c "import pytest" 2>/dev/null; then \
		echo -e "$(RED)ERROR: pytest not found. Run 'make setup-cli-dev' first.$(NC)"; exit 1; \
	fi
	@if ! $(PYTHON) -c "import lma_sdk" 2>/dev/null; then \
		echo -e "$(RED)ERROR: lma_sdk not importable. Run 'make setup-cli-dev' first.$(NC)"; exit 1; \
	fi
	$(PYTHON) -m pytest integ-tests/ --stack-name "$(INTEG_STACK)" -m "not live"
	@echo -e "$(GREEN)✅ Integration tests passed against '$(INTEG_STACK)'!$(NC)"

# The scheduled-pipeline entry point (nightly_integ_tests in .gitlab-ci.yml).
# Differs from integ-tests in exactly two ways, both about a run nobody is
# watching:
#   --no-skips  a skipped test fails the run. The opt-in audio test is the whole
#               reason the schedule exists, and it skips itself when its
#               credentials or optional dependencies are missing, so without this
#               a lapsed secret reports green having tested none of the pipeline.
#   --junit-xml a report the CI UI can show per test, since nobody reads the log
#               of a run that passed.
# The Cognito user comes from LMA_TEST_USER_SECRET_ID (Secrets Manager) rather
# than LMA_TEST_PASSWORD, so the password is never a CI variable — see
# integ-tests/cognito_test_user.py.
INTEG_JUNIT ?= integ-tests-report.xml
integ-tests-nightly: ## Integration tests for the scheduled pipeline: skips fail, JUnit report (Usage: make integ-tests-nightly STACK=<name> [SHARD=K/N])
	@echo -e "$(CYAN)Running scheduled LMA integration tests against '$(INTEG_STACK)'...$(NC)"
	@if ! $(PYTHON) -c "import lma_sdk" 2>/dev/null; then \
		echo -e "$(RED)ERROR: lma_sdk not importable. Run 'make setup-cli-dev' first.$(NC)"; exit 1; \
	fi
	@if ! $(PYTHON) -c "import pycognito, websockets" 2>/dev/null; then \
		echo -e "$(RED)ERROR: pycognito / websockets missing — the audio test would skip.$(NC)"; \
		echo -e "$(YELLOW)   Run: $(PIP) install -r integ-tests/requirements.txt$(NC)"; exit 1; \
	fi
	@if [ -z "$$LMA_TEST_USER_SECRET_ID" ] && [ -z "$$LMA_TEST_USERNAME" ]; then \
		echo -e "$(RED)ERROR: no Cognito test user configured — the audio test would skip.$(NC)"; \
		echo -e "$(YELLOW)   Set LMA_TEST_USER_SECRET_ID (preferred) or LMA_TEST_USERNAME/LMA_TEST_PASSWORD.$(NC)"; \
		exit 1; \
	fi
	$(PYTHON) -m pytest integ-tests/ --stack-name "$(INTEG_STACK)" -m "not live" \
		--no-skips --durations=30 --junit-xml="$(INTEG_JUNIT)" $(if $(SHARD),--shard "$(SHARD)")
	@echo -e "$(GREEN)✅ Scheduled integration tests passed against '$(INTEG_STACK)'!$(NC)"

integ-tests-live: ## Integration tests INCLUDING a real VP meeting join (Usage: make integ-tests-live STACK=<name> PLATFORM=ZOOM MEETING_ID=<id> [MEETING_PASSWORD=<pw>])
ifndef MEETING_ID
	$(error MEETING_ID is not set. Usage: make integ-tests-live STACK=<name> PLATFORM=ZOOM MEETING_ID=<id> [MEETING_PASSWORD=<pw>])
endif
	@echo -e "$(CYAN)Running LMA integration tests (incl. live $(or $(PLATFORM),ZOOM) join) against '$(INTEG_STACK)'...$(NC)"
	$(PYTHON) -m pytest integ-tests/ --stack-name "$(INTEG_STACK)" \
		--vp-platform "$(or $(PLATFORM),ZOOM)" \
		--vp-meeting-id "$(MEETING_ID)" \
		--vp-meeting-password "$(MEETING_PASSWORD)"
	@echo -e "$(GREEN)✅ Integration tests (incl. live join) passed against '$(INTEG_STACK)'!$(NC)"

# Deploy (create-if-new / update-if-exists) from local code, then run the
# integration tests. This is the one-shot entry point the 'run integration tests'
# Claude skill uses. STACK defaults to 'lma-integtest1' here (not 'LMA') so the
# skill never touches a prod-looking stack by accident. ADMIN_EMAIL is required
# only when the stack does not yet exist.
INTEG_DEPLOY_STACK ?= $(or $(STACK),$(LMA_STACK_NAME),lma-integtest1)
integ-deploy-and-test: ## Deploy (create/update) a stack from local code, then run integ-tests (Usage: make integ-deploy-and-test [STACK=<name>] [ADMIN_EMAIL=<email>])
	@if ! $(PYTHON) -c "import lma_sdk" 2>/dev/null; then \
		echo -e "$(RED)ERROR: lma_sdk not importable. Run 'make setup-cli-dev' first.$(NC)"; exit 1; \
	fi
	@STACK_NAME="$(INTEG_DEPLOY_STACK)"; \
	if aws cloudformation describe-stacks --stack-name "$$STACK_NAME" >/dev/null 2>&1; then \
		echo -e "$(CYAN)Stack '$$STACK_NAME' exists — updating from local code...$(NC)"; \
		$(VENV_DIR)/bin/lma deploy --stack-name "$$STACK_NAME" --from-code . --wait; \
	else \
		if [ -z "$(ADMIN_EMAIL)" ]; then \
			echo -e "$(RED)ERROR: stack '$$STACK_NAME' does not exist and ADMIN_EMAIL is not set.$(NC)"; \
			echo -e "$(YELLOW)Usage: make integ-deploy-and-test STACK=$$STACK_NAME ADMIN_EMAIL=you@example.com$(NC)"; \
			exit 1; \
		fi; \
		echo -e "$(CYAN)Stack '$$STACK_NAME' not found — creating from local code (admin=$(ADMIN_EMAIL))...$(NC)"; \
		$(VENV_DIR)/bin/lma deploy --stack-name "$$STACK_NAME" --from-code . --admin-email "$(ADMIN_EMAIL)" --wait; \
	fi
	@$(MAKE) integ-tests STACK="$(INTEG_DEPLOY_STACK)"

##@ Security Testing
# The live-stack security tests and the offline set: see docs/security-testing.md
# and the 'run-security-tests' Claude skill. STACK, REGION and AWS_PROFILE=default
# as for integ-tests. Reports go to scratch/ (ignored by git).
SECTEST_STACK ?= $(or $(STACK),$(LMA_STACK_NAME))
SECTEST_REGION_ENV = $(if $(REGION),LMA_REGION=$(REGION) AWS_DEFAULT_REGION=$(REGION))

# Throwaway users, one throwaway meeting and a temporary app client, all deleted
# afterwards; the web UI app client's ID token lifetime is shortened for one
# sign-in and restored at once. --no-skips: a missing dependency fails the run
# rather than reporting green having checked nothing. SHARED=1 leaves the web UI
# app client alone (the expiry check is then not run), for a stack other runs use.
stacktest-rbac: ## Live access tests: roles, tokens, meeting access, other entry points (Usage: make stacktest-rbac STACK=<name> [REGION=<region>])
ifeq ($(SECTEST_STACK),)
	$(error Set STACK to the deployed stack to test. Usage: make stacktest-rbac STACK=<name> [REGION=<region>])
endif
	@if ! $(PYTHON) -c "import lma_sdk, pycognito, websockets, graphql" 2>/dev/null; then \
		echo -e "$(RED)ERROR: test dependencies missing. Run 'make setup-cli-dev' and '$(PIP) install -r integ-tests/requirements.txt'.$(NC)"; \
		exit 1; \
	fi
	@echo -e "$(CYAN)Running the live access tests against '$(SECTEST_STACK)'...$(NC)"
	$(SECTEST_REGION_ENV) $(if $(filter 1 true yes,$(SHARED)),LMA_SECTEST_NO_CLIENT_CHANGE=1) \
		$(PYTHON) -m pytest integ-tests/test_role_access.py integ-tests/test_security_access.py \
		--stack-name "$(SECTEST_STACK)" --no-skips $(RBAC_PYTEST_ARGS)
	@echo -e "$(GREEN)✅ Live access tests passed against '$(SECTEST_STACK)'. Report: scratch/api-test-results/report.md$(NC)"

# OWASP ZAP in Docker. Passive unless ZAP_ACTIVE=1, which sends attack payloads
# and mutations: for a throwaway stack only. WARN-only: findings do not fail it.
stacktest-zap: ## OWASP ZAP scan of the GraphQL API, web UI and MCP endpoint (Usage: make stacktest-zap STACK=<name> [REGION=<region>] [ZAP_ACTIVE=1] [TARGETS=graphql,web,mcp])
ifeq ($(SECTEST_STACK),)
	$(error Set STACK to the deployed stack to scan. Usage: make stacktest-zap STACK=<name> [REGION=<region>] [ZAP_ACTIVE=1])
endif
	@if ! $(PYTHON) -c "import boto3, pycognito, graphql" 2>/dev/null; then \
		echo -e "$(RED)ERROR: dependencies missing. Run '$(PIP) install -r scripts/security/requirements-zap-job.txt'.$(NC)"; \
		exit 1; \
	fi
	$(SECTEST_REGION_ENV) $(PYTHON) scripts/security/zap_scan.py --stack-name "$(SECTEST_STACK)" \
		$(if $(REGION),--region "$(REGION)") \
		$(if $(filter 1 true yes,$(ZAP_ACTIVE)),--active) \
		$(if $(TARGETS),--targets "$(TARGETS)")

# Offline: SRT and the static role checks. With STACK: also stacktest-rbac and a
# passive stacktest-zap. Every step runs; summary in scratch/security-results/.
# SNAPSHOT=1 then writes this run's counts-only snapshot to
# security/test-results/<VERSION>/ (committed; see the curate-security-results
# skill). REPLACE=1 overwrites an existing snapshot of that version.
# ALLOW_FAILURES=1 writes one that records failures, once they are handled.
SNAPSHOT_FLAGS = $(if $(filter 1 true yes,$(REPLACE)),--replace) \
	$(if $(filter 1 true yes,$(ALLOW_FAILURES)),--allow-failures)
security-results: ## Run the security tests as a set (Usage: make security-results [STACK=<name> REGION=<region>] [SNAPSHOT=1])
	$(SECTEST_REGION_ENV) $(PYTHON) scripts/security/security_results.py \
		$(if $(STACK),--stack-name "$(STACK)") $(if $(REGION),--region "$(REGION)") \
		$(if $(filter 1 true yes,$(SNAPSHOT)),--snapshot $(SNAPSHOT_FLAGS))

# Curate the snapshot from reports already on disk, without running the tests.
# CURATE_ARGS passes flags through, e.g. --stack-version 0.4.1 --commit live-rbac=<sha>.
security-snapshot: ## Write security/test-results/<VERSION>/ from existing local reports (Usage: make security-snapshot [CURATE_ARGS=...])
	$(PYTHON) scripts/security/curate_snapshot.py $(SNAPSHOT_FLAGS) $(CURATE_ARGS)

##@ Product Demo Recording
# Narrated demo videos of the web UI: see .claude/skills/product-demo.md. The
# recording is driven by the agent between browser steps; these only check the
# tools and prepare a sign-in.

ux-record-deps: ## Check the tools the demo recorder needs (ffmpeg, ffprobe, boto3, Pillow)
	@$(PYTHON) scripts/ux_recorder.py deps

# Creates a REAL Cognito user with a known password in the stack's pool, for
# recording as a role other than your own (GROUP=User for a non-admin).
ux-test-session: ## Create a throwaway sign-in for a demo (Usage: make ux-test-session STACK_NAME=<stack> [REGION=...] [GROUP=Admin|User] [EMAIL_DOMAIN=...])
ifndef STACK_NAME
	$(error STACK_NAME is not set. Usage: make ux-test-session STACK_NAME=<stack-name> [REGION=... GROUP=...])
endif
	@echo "Creating a throwaway sign-in for $(STACK_NAME)..."
	@$(PYTHON) scripts/ux_test_session.py setup $(STACK_NAME) \
	    --group $(if $(GROUP),$(GROUP),Admin) \
	    $(if $(REGION),--region $(REGION),) \
	    $(if $(EMAIL_DOMAIN),--email-domain $(EMAIL_DOMAIN),)
	@echo -e "$(YELLOW)Record as described in .claude/skills/product-demo.md$(NC)"
	@echo -e "$(YELLOW)Remember to run the teardown command printed above.$(NC)"

##@ UI Development
# Usage: make ui-start STACK_NAME=<stack-name>
ui-start: ## Start UI dev server (requires STACK_NAME for .env generation)
ifndef STACK_NAME
	$(error STACK_NAME is not set. Usage: make ui-start STACK_NAME=<your-stack-name>)
endif
	@if [ -n "$(STACK_NAME)" ]; then \
		echo "Retrieving .env configuration from stack $(STACK_NAME)..."; \
		ENV_CONTENT=$$(aws cloudformation describe-stacks \
			--stack-name $(STACK_NAME) \
			--query "Stacks[0].Outputs[?OutputKey=='LocalUITestingEnv'].OutputValue" \
			--output text 2>/dev/null); \
		if [ -z "$$ENV_CONTENT" ] || [ "$$ENV_CONTENT" = "None" ]; then \
			echo -e "$(RED)ERROR: Could not retrieve LocalUITestingEnv from stack $(STACK_NAME)$(NC)"; \
			echo -e "$(YELLOW)Make sure the stack exists and has completed deployment.$(NC)"; \
			exit 1; \
		fi; \
		echo "$$ENV_CONTENT" \
			| tr ' ' '\n' \
			> $(UI_DIR)/.env; \
		echo -e "$(GREEN)✅ Created $(UI_DIR)/.env from stack outputs$(NC)"; \
	fi
	@if [ ! -f $(UI_DIR)/.env ]; then \
		echo -e "$(RED)ERROR: $(UI_DIR)/.env not found$(NC)"; \
		echo -e "$(YELLOW)Either provide STACK_NAME to auto-generate, or create .env manually.$(NC)"; \
		echo -e "$(YELLOW)Usage: make ui-start STACK_NAME=<your-stack-name>$(NC)"; \
		exit 1; \
	fi
	@echo "Installing UI dependencies..."
	cd $(UI_DIR) && $(NPM_CI)
	@echo "Starting UI development server..."
	cd $(UI_DIR) && npm run start

##@ Virtual Participant Development
# Usage:
#   make vp-start STACK_NAME=<stack> PLATFORM=<WEBEX|ZOOM|TEAMS|CHIME|GOOGLE_MEET> MEETING_ID=<id> \
#                 [MEETING_PASSWORD=<pw>] [DEV=1] [REUSE_ENV=1]
#
# Runs the Virtual Participant Docker container locally against a deployed LMA
# stack. See docs/virtual-participant-local-dev.md for the recommended EC2 +
# VSCode Remote-SSH + VNC workflow.
vp-start: ## Run VP locally via Docker (requires STACK_NAME, PLATFORM, MEETING_ID)
ifndef STACK_NAME
	$(error STACK_NAME is not set. Usage: make vp-start STACK_NAME=<stack> PLATFORM=<platform> MEETING_ID=<id> [MEETING_PASSWORD=<pw>] [DEV=1] [REUSE_ENV=1])
endif
ifndef PLATFORM
	$(error PLATFORM is not set. Must be one of: WEBEX, ZOOM, TEAMS, CHIME, GOOGLE_MEET)
endif
ifndef MEETING_ID
	$(error MEETING_ID is not set)
endif
	@EXTRA_FLAGS=""; \
	if [ "$(DEV)" = "1" ]; then EXTRA_FLAGS="$$EXTRA_FLAGS --dev"; fi; \
	if [ "$(REUSE_ENV)" = "1" ]; then EXTRA_FLAGS="$$EXTRA_FLAGS --reuse-env"; fi; \
	echo -e "$(CYAN)Launching Virtual Participant locally (stack=$(STACK_NAME), platform=$(PLATFORM), id=$(MEETING_ID))$(NC)"; \
	cd $(VP_BACKEND_DIR) && bash local-test.sh $$EXTRA_FLAGS "$(STACK_NAME)" "$(PLATFORM)" "$(MEETING_ID)" "$(MEETING_PASSWORD)"

vp-start-dev: ## Run VP locally in dev mode (auto-reload on src changes); same args as vp-start
	@$(MAKE) vp-start DEV=1 STACK_NAME="$(STACK_NAME)" PLATFORM="$(PLATFORM)" MEETING_ID="$(MEETING_ID)" MEETING_PASSWORD="$(MEETING_PASSWORD)" REUSE_ENV="$(REUSE_ENV)"

vp-start-reuse: ## Run VP locally reusing existing .env.local (keeps manually-set secrets); same args as vp-start
	@$(MAKE) vp-start REUSE_ENV=1 STACK_NAME="$(STACK_NAME)" PLATFORM="$(PLATFORM)" MEETING_ID="$(MEETING_ID)" MEETING_PASSWORD="$(MEETING_PASSWORD)" DEV="$(DEV)"

vp-stop: ## Stop and remove the local VP container (lma-vp-local-test)
	@if docker ps -a --format '{{.Names}}' | grep -q "^lma-vp-local-test$$"; then \
		echo "Stopping and removing lma-vp-local-test..."; \
		docker rm -f lma-vp-local-test; \
		echo -e "$(GREEN)✅ Container removed.$(NC)"; \
	else \
		echo -e "$(YELLOW)No lma-vp-local-test container found.$(NC)"; \
	fi

vp-logs: ## Tail logs for the local VP container (dev mode)
	@docker logs -f lma-vp-local-test

vp-shell: ## Open a shell inside the running local VP container
	@docker exec -it lma-vp-local-test /bin/bash

##@ Security
# Sample Security Review Tool (https://github.com/aws-samples/sample-security-review-tool).
#
# SRT reads and rewrites .srt/issues.json on every assessment, so that file is
# generated output and is gitignored. The reviewed decisions are kept separately
# in .srt/suppressions.json, which IS tracked: `srt-seed` restores issues.json
# from it on a fresh checkout (CI, new clone) so a scan starts from the reviewed
# state, and `srt-save-suppressions` refreshes it after triage.
# See docs/security-scanning.md.
SRT_ISSUES := .srt/issues.json
SRT_SUPPRESSIONS := .srt/suppressions.json

srt: ## Run full SRT workflow (setup, scan, then prompt to open dashboard)
	@$(MAKE) srt-setup
	@$(MAKE) srt-scan
	@echo ""
	@echo -e "$(CYAN)Open the dashboard to triage findings:$(NC) make srt-fix"

srt-setup: ## Download and configure SRT (pin via SRT_VERSION env var)
	$(PYTHON) scripts/srt/setup.py

srt-scan: srt-seed ## Run SRT assessment (non-zero exit in CI on open findings)
	$(PYTHON) scripts/srt/run.py

srt-seed: ## Restore .srt/issues.json from the tracked decisions (no-op if it exists)
	@if [ -f $(SRT_ISSUES) ]; then \
		echo "$(SRT_ISSUES) already present — leaving it as-is."; \
	elif [ -f $(SRT_SUPPRESSIONS) ]; then \
		mkdir -p .srt && cp $(SRT_SUPPRESSIONS) $(SRT_ISSUES); \
		echo -e "$(GREEN)✅ Seeded $(SRT_ISSUES) from $(SRT_SUPPRESSIONS)$(NC)"; \
	else \
		echo -e "$(YELLOW)No $(SRT_SUPPRESSIONS) found — scanning without prior decisions.$(NC)"; \
	fi

srt-save-suppressions: ## Refresh .srt/suppressions.json from .srt/issues.json after triage (then commit it)
	@test -f $(SRT_ISSUES) || { echo -e "$(RED)ERROR: $(SRT_ISSUES) not found. Run 'make srt-scan' first.$(NC)"; exit 1; }
	@$(PYTHON) -c "import json; p='$(SRT_ISSUES)'; q='$(SRT_SUPPRESSIONS)'; d=json.load(open(p)); k=sorted([i for i in d if i.get('status')=='suppressed'], key=lambda i: (str(i.get('source')), str(i.get('check_id')), str(i.get('path')), str(i.get('line')))); f=open(q,'w'); json.dump(k,f,indent=2); f.write('\n'); f.close(); print('Wrote %d decisions to %s (from %d entries in %s)' % (len(k), q, len(d), p))"

srt-fix: ## Open the SRT dashboard for interactive triage
	$(PYTHON) scripts/srt/fix.py

srt-clean: ## Remove vendored layer trees, .aws-sam, out/, node_modules, scan artifacts (preserves SRT binary, venv, issues.json, .checksum)
	$(PYTHON) scripts/srt/clean.py --apply

srt-clean-preview: ## Show what `make srt-clean` would remove without deleting anything
	$(PYTHON) scripts/srt/clean.py

srt-clean-checksums: ## Remove **/.checksum cache files (forces full rebuild on next make/publish)
	@find . -name .checksum -not -path './.git/*' -print -delete | wc -l | xargs -I{} echo "Removed {} .checksum file(s)"

srt-migrate-dsr: ## Migrate suppressions from .dsr/issues.json → .srt/issues.json (one-shot)
	$(PYTHON) scripts/srt/migrate_dsr_to_srt.py $(if $(FORCE),--force,)

##@ Publishing & Deployment

# Usage: make publish BUCKET=<bucket-basename> PREFIX=<prefix> REGION=<region> [PUBLIC=true]
publish: ## Run publish.sh to build and upload all artifacts to S3
ifndef BUCKET
	$(error BUCKET is not set. Usage: make publish BUCKET=<bucket-basename> PREFIX=<prefix> REGION=<region>)
endif
ifndef PREFIX
	$(error PREFIX is not set. Usage: make publish BUCKET=<bucket-basename> PREFIX=<prefix> REGION=<region>)
endif
ifndef REGION
	$(error REGION is not set. Usage: make publish BUCKET=<bucket-basename> PREFIX=<prefix> REGION=<region>)
endif
	@echo "Publishing LMA artifacts..."
	@if [ "$(PUBLIC)" = "true" ]; then \
		bash publish.sh $(BUCKET) $(PREFIX) $(REGION) public; \
	else \
		bash publish.sh $(BUCKET) $(PREFIX) $(REGION); \
	fi

##@ Version Management
# Usage: make version V=0.3.1
.PHONY: version
version: ## Update version everywhere (Usage: make version V=x.y.z)
ifndef V
	$(error VERSION is not set. Usage: make version V=x.y.z)
endif
	@echo "$(V)" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+' || \
		(echo -e "$(RED)ERROR: '$(V)' is not a valid version. Use format: x.y.z$(NC)" && exit 1)
	@echo "Updating version to $(V)..."
	@# Root VERSION file
	@echo "$(V)" > $(VERSION_FILE)
	@echo "  $(VERSION_FILE)"
	@# LMA SDK
	@sed -i.bak 's/^version = ".*"/version = "$(V)"/' lib/lma_sdk/pyproject.toml && rm -f lib/lma_sdk/pyproject.toml.bak
	@echo "  lib/lma_sdk/pyproject.toml"
	@sed -i.bak 's/^__version__ = ".*"/__version__ = "$(V)"/' lib/lma_sdk/lma_sdk/__init__.py && rm -f lib/lma_sdk/lma_sdk/__init__.py.bak
	@echo "  lib/lma_sdk/lma_sdk/__init__.py"
	@# LMA CLI
	@sed -i.bak 's/^version = ".*"/version = "$(V)"/' lib/lma_cli_pkg/pyproject.toml && rm -f lib/lma_cli_pkg/pyproject.toml.bak
	@echo "  lib/lma_cli_pkg/pyproject.toml"
	@sed -i.bak 's/^__version__ = ".*"/__version__ = "$(V)"/' lib/lma_cli_pkg/lma_cli/__init__.py && rm -f lib/lma_cli_pkg/lma_cli/__init__.py.bak
	@echo "  lib/lma_cli_pkg/lma_cli/__init__.py"
	@# Solution profile manifest, in the contract's version form (0.4.1.dev1 -> 0.4.1-dev1)
	@$(PYTHON) scripts/solution_profile/check.py --stamp-version $(V)
	@echo -e "$(GREEN)✅ Version updated to $(V) in all locations$(NC)"

##@ Git Workflow
# Both helpers share _commit-push below. They stage modifications to tracked
# files only (`git add -u`) and refuse to run while any untracked file is
# present: this is a public repository and working trees here routinely contain
# large local scratch directories, so `git add .` is the wrong default. A path
# that only ever exists in your own working tree belongs in .git/info/exclude
# (local, not shared) rather than in .gitignore, which would hide it from
# `git add` and `git status` for every contributor and on every branch — some
# branches legitimately track paths that others treat as scratch. The
# staged diffstat and the generated message are shown and confirmed before
# anything is committed or pushed, and the prompt names the resolved upstream
# (remote + branch) rather than just the local branch, because upstreams differ
# per branch in this repo. Committing straight to develop or main is refused by
# default: changes normally go through a pull request. Pass ALLOW_SHARED_BRANCH=1
# to commit onto a shared branch deliberately. _commit-preflight runs those
# checks up front too, so `make commit` fails in a second rather than after the
# full test run.
.PHONY: commit fastcommit _commit-preflight _commit-push

commit: _commit-preflight lint test ## Lint, test, stage tracked changes, then review + confirm before push
	@$(MAKE) --no-print-directory _commit-push

fastcommit: ## Stage tracked changes, then review + confirm before push (no lint/test)
	@$(MAKE) --no-print-directory _commit-push

_commit-preflight:
	@if [ ! -t 0 ]; then \
		echo -e "$(RED)ERROR: this target needs an interactive terminal (it asks for confirmation).$(NC)"; \
		exit 1; \
	fi
	@BRANCH=$$(git rev-parse --abbrev-ref HEAD); \
	UPSTREAM=$$(git rev-parse --abbrev-ref --symbolic-full-name @{upstream} 2>/dev/null); \
	SHARED=; \
	case "$$BRANCH" in develop|main) SHARED=1;; esac; \
	case "$$UPSTREAM" in */develop|*/main) SHARED=1;; esac; \
	if [ -n "$$SHARED" ] && [ -n "$(ALLOW_SHARED_BRANCH)" ]; then \
		echo -e "$(YELLOW)Committing directly onto $$BRANCH -> $${UPSTREAM:-no upstream} (ALLOW_SHARED_BRANCH set).$(NC)"; \
	elif [ -n "$$SHARED" ]; then \
		echo -e "$(RED)ERROR: refusing to commit onto a shared branch ($$BRANCH -> $${UPSTREAM:-no upstream}).$(NC)"; \
		echo -e "$(YELLOW)Create a branch ('git switch -c feature/<name>') and open a pull request instead,$(NC)"; \
		echo -e "$(YELLOW)or re-run with ALLOW_SHARED_BRANCH=1 to commit here deliberately.$(NC)"; \
		exit 1; \
	fi
	@UNTRACKED=$$(git ls-files --others --exclude-standard); \
	if [ -n "$$UNTRACKED" ]; then \
		echo -e "$(RED)ERROR: untracked files present — refusing to commit.$(NC)"; \
		echo "$$UNTRACKED"; \
		echo -e "$(YELLOW)Stage them explicitly ('git add <path>'), remove them, or — if they are local-only$(NC)"; \
		echo -e "$(YELLOW)paths — add them to .git/info/exclude, then re-run.$(NC)"; \
		exit 1; \
	fi

_commit-push: _commit-preflight
	@git add -u
	@if git diff --cached --quiet; then \
		echo -e "$(YELLOW)Nothing staged — no tracked files changed.$(NC)"; \
		exit 0; \
	fi; \
	TARGET=$$(git rev-parse --abbrev-ref --symbolic-full-name @{upstream} 2>/dev/null); \
	if [ -z "$$TARGET" ]; then \
		TARGET="$$(git rev-parse --abbrev-ref HEAD) (no upstream set — 'git push' will ask for one)"; \
	fi; \
	echo -e "$(CYAN)Staged changes:$(NC)"; \
	git diff --cached --stat; \
	echo "Generating commit message via Bedrock..."; \
	COMMIT_MESSAGE=$$(bash scripts/generate_commit_message.sh) || exit 1; \
	echo -e "$(CYAN)Commit message:$(NC) $$COMMIT_MESSAGE"; \
	read -r -p "Commit the above and push to $$TARGET? [y/N] " REPLY; \
	case "$$REPLY" in \
		[yY]|[yY][eE][sS]) ;; \
		*) echo -e "$(YELLOW)Aborted — changes left staged.$(NC)"; exit 0;; \
	esac; \
	git commit -m "$$COMMIT_MESSAGE" && git push

##@ Documentation
docs: docs-build ## Build and serve the documentation site locally
	@echo "Starting docs preview server..."
	cd docs-site && npm run preview

docs-setup: ## One-time docs site setup (symlinks + npm install)
	@echo "Setting up documentation site..."
	cd docs-site && bash setup.sh && npm install
	@echo -e "$(GREEN)✅ Docs site setup complete!$(NC)"

docs-build: docs-setup ## Build documentation site (no serve)
	@echo "Ensuring docs have frontmatter..."
	cd docs-site && bash add-frontmatter.sh
	@echo "Syncing sidebar with new docs..."
	cd docs-site && node sync-sidebar.mjs
	@echo "Building documentation site..."
	cd docs-site && npm run build
	@echo -e "$(GREEN)✅ Docs site built! $(NC)"
	@echo "Preview at: http://localhost:4321"

docs-dev: docs-setup ## Start docs dev server with hot reload
	cd docs-site && npm run dev

docs-deploy: docs-build ## Deploy docs to GitHub Pages (from local build)
	@echo "Deploying to GitHub Pages..."
	touch docs-site/dist/.nojekyll
	cd docs-site && npx gh-pages -d dist --dotfiles --repo https://github.com/aws-samples/amazon-transcribe-live-meeting-assistant.git
	@echo -e "$(GREEN)✅ Docs deployed to GitHub Pages!$(NC)"
	@echo "View at: https://aws-samples.github.io/amazon-transcribe-live-meeting-assistant/"

##@ Clean
clean: ## Clean all build artifacts
	@echo "Cleaning build artifacts..."
	-rm -rf $(AI_STACK_DIR)/out
	-rm -rf $(AI_STACK_DIR)/.aws-sam
	-rm -rf $(WEBSOCKET_DIR)/out
	-rm -rf $(VP_DIR)/build $(VP_DIR)/dist
	-rm -rf $(VP_BACKEND_DIR)/build $(VP_BACKEND_DIR)/dist
	-rm -rf $(VENV_DIR)
	-rm -f $(UI_TEST_CHECKSUM_FILE)
	-rm -f $(UI_LINT_CHECKSUM_FILE)
	@echo -e "$(GREEN)✅ Clean complete!$(NC)"

clean-node: ## Clean all node_modules directories
	@echo "Cleaning node_modules directories..."
	-rm -rf $(UI_DIR)/node_modules
	-rm -rf $(WEBSOCKET_APP_DIR)/node_modules
	-rm -rf $(VP_BACKEND_DIR)/node_modules
	-rm -rf node_modules
	@echo -e "$(GREEN)✅ node_modules cleaned!$(NC)"

clean-all: clean clean-node ## Clean everything (build artifacts + node_modules)
