# Makefile - shortcut commands for the cndb project (run `make help` for all targets)
# Convention: this file only wires commands together; cross-platform / multi-line logic lives
# in scripts/ so every target stays readable at a glance.

.DEFAULT_GOAL := help

# Block the LD_LIBRARY_PATH injected by the IDE (Trae): its bundled old libsqlite3 lacks the
# sqlite3_deserialize symbol, which crashes the Python sqlite3 module and makes backend tests
# hang. GNU Make passes parent environment variables through to recipes by default; after
# unexport, no `uv run` child process inherits it any more.
unexport LD_LIBRARY_PATH

PACKAGE := cndb

# Gate concurrency (two serial phases, each owning the CPU so pytest and vitest never compete):
# PYTEST_JOBS: pytest-xdist worker count, derived from the local logical core count (cap 32)
#   instead of a hard-coded 16 — measured on 24 cores: n16=89s / n24=70s; worksteal steals
#   tasks dynamically and removes the long tail of whole-file loadfile distribution;
#   low-spec machines / CI override explicitly: make check PYTEST_JOBS=8.
#   Evaluation order: nproc (POSIX / MSYS, sub-millisecond) -> uv run python (cross-platform
#   fallback) -> 8.
CPU_COUNT := $(shell nproc 2>/dev/null | tr -dc 0-9)
ifeq ($(strip $(CPU_COUNT)),)
CPU_COUNT := $(shell uv run python -c "import os; print(os.cpu_count() or 0)" 2>/dev/null | tr -dc 0-9)
endif
ifeq ($(strip $(CPU_COUNT)),)
CPU_COUNT := 8
endif
# Cap 32: beyond that, scheduling and memory overhead of extra workers outweighs the gain
# (measured on 24 cores, 24 workers were already close to optimal).
# Use ifndef + := instead of ?=: the worker count is deterministic, one evaluation is enough,
# and each recipe expansion no longer forks a shell.
ifndef PYTEST_JOBS
ifneq ($(shell test $(CPU_COUNT) -gt 32 && echo y),)
PYTEST_JOBS := 32
else
PYTEST_JOBS := $(CPU_COUNT)
endif
endif
# Exported so scripts/retest.py / scripts/verify_changed.py reuse the same concurrency value
export PYTEST_JOBS
# VITEST_MAX_WORKERS: vitest worker count; left empty, frontend/vite.config.ts derives
#   min(16, CPU quota) from the container quota. Cloud / low-core machines override explicitly:
#   make check VITEST_MAX_WORKERS=4. Only exported when non-empty, so an empty value never
#   overrides the automatic derivation.
VITEST_MAX_WORKERS ?=
ifneq ($(strip $(VITEST_MAX_WORKERS)),)
export VITEST_MAX_WORKERS
endif

# dev target bind address / port, overridable on the command line:
# make dev DEV_HOST=127.0.0.1 DEV_PORT=8000
DEV_HOST ?= 0.0.0.0
DEV_PORT ?= 8772
# Ports released before `make dev` starts: backend DEV_PORT + the fixed Vite port 5173
# (see cli/main.py dev())
DEV_PORTS ?= $(DEV_PORT) 5173

# uvx temporary environments ignore the project [tool.uv.index]; pin the mirror explicitly
UVX_INDEX := --default-index https://mirrors.cloud.tencent.com/pypi/simple

# Frontend dependency stamp: refreshed by make after a successful pnpm install; when lock /
# package.json are unchanged the step is skipped at zero cost
FRONTEND_DEPS := frontend/node_modules/.make-sync

.PHONY: help env-guard sync free-dev-ports dev seed frontend-sync frontend-static frontend-coverage frontend-test frontend-build check-build \
        build clean test cov lint typecheck e2e e2e-dev bench gitkeep-check adr-check constraint-check \
        check-fast check-docs check-backend check-frontend flow verify-changed verify-changed-plan retest gate-report \
        preflight cov-changed adr-index context-split long-files changelog-add \n        context constraints adr \
        e2e-affected e2e-reuse check bump pub push pack-doctor pack pack-cache-clean \n        ops ops-check ops-maintain ops-apply \
        docker-dev docker-dev-down docker-stop docker-build docker-export dd ds ddd db de \
        patch minor major

# ── Development ───────────────────────────────────────────────────────

help: ## Show this help
	@uv run python scripts/help.py $(MAKEFILE_LIST)

env-guard: ## Environment check (blocks LD_LIBRARY_PATH pollution: an old libsqlite3 without sqlite3_deserialize hangs tests)
	@uv run python scripts/check_env.py

sync: ## Install backend dev dependencies + git pre-commit hooks (prek)
	uv sync --extra dev
	uv run prek install --force

free-dev-ports: ## Kill stale processes holding dev ports (backend DEV_PORT=8772, frontend 5173; override with DEV_PORTS)
	@uv run python scripts/free_ports.py $(DEV_PORTS)

dev: env-guard free-dev-ports $(FRONTEND_DEPS) ## Dev mode: release stale ports, then start backend + frontend (uvicorn + Vite, Ctrl+C stops both)
	uv run cndb dev --host $(DEV_HOST) --port $(DEV_PORT)

seed: ## Seed demo data for dev / e2e (recreates the DB; refuses when user data exists, use cndb seed --force)
	uv run cndb seed

# ── Frontend ──────────────────────────────────────────────────────────

$(FRONTEND_DEPS): frontend/package.json frontend/pnpm-lock.yaml frontend/pnpm-workspace.yaml
	cd frontend && pnpm install --frozen-lockfile
	@uv run python -c "import pathlib; pathlib.Path('$(FRONTEND_DEPS)').touch()"

frontend-sync: $(FRONTEND_DEPS) ## Install frontend dependencies (pnpm; skipped when lock / package.json are unchanged)

frontend-static: $(FRONTEND_DEPS) ## Frontend static checks (patch + tsc + eslint)
	cd frontend && pnpm check

frontend-coverage: $(FRONTEND_DEPS) ## Frontend tests + dual coverage thresholds (text + json-summary)
	cd frontend && pnpm test:coverage

# F1 targeted frontend feedback (AGENTS 3.3): run only the directory / file you just touched.
# Unlike `make verify-changed`, this passes the path straight to vitest (no `related` graph
# computation), so a single directory is typically a few seconds — use it as the inner-loop
# feedback for a small edit. It is NOT a substitute for the F2 gate before committing.
#   make test-frontend DIR=src/pages/home
#   make test-frontend DIR=src/pages/home/HomeLanding.test.tsx
DIR ?= src
test-frontend: $(FRONTEND_DEPS) ## F1 frontend loop: run vitest on DIR only (default src; budget <=60s)
	cd frontend && pnpm exec vitest run $(DIR)

frontend-build: $(FRONTEND_DEPS) ## Build the frontend (Vite, output goes to src/cndb/static/)
	cd frontend && pnpm build

# F2 build gate — the CI `frontend-build` job runs `pnpm build` (its tail runs
# check-browser-compat --strict + scene-gate) plus `pnpm bundle:budget`, and no other make target
# covered those two steps, so "make check green, CI frontend-build red" was bound to happen:
# the 2026-11-29 tutorial chunk at 33.70 > 33.69 KiB leaked to CI exactly this way (a Chromium 81
# compat violation or a whiteboard sub-app size overrun would leak the same way). This target
# reproduces the CI result locally in one shot. Measured ~21s, so it is F2 — never fold it into the
# F0 `check-fast`. Output goes to src/cndb/static/ (already gitignored, .gitkeep kept), so it never
# dirties the worktree.
check-build: $(FRONTEND_DEPS) ## F2 build gate: pnpm build (compat + scene-gate) + bundle-budget, same as CI frontend-build
	cd frontend && pnpm build
	cd frontend && pnpm bundle:budget

# ── Quality gates ─────────────────────────────────────────────────────

lint: ## Backend style checks (ruff check + format, same scope as CI: src + tests)
	uv run ruff check src tests --cache-dir .ruff_cache
	uv run ruff format --check src tests

typecheck: ## Backend type checks (pyrefly)
	uv run pyrefly check -j 0

# 成功只打一行（约 30 B），失败才输出完整报告 —— 详见 scripts/pytest_quiet.py 的文件头。
# 为什么不是加 -q：pytest.ini 已有 -q，但 xdist 仍为每个 worker 打 "bringing up nodes..."
# 与进度点，实测 make flow 成功输出 10.9 KB / 137 行，其中 117 行是零信息的点。
# 需要流式输出（盯长跑）：make test PYTEST_VERBOSE=1
PYTEST_VERBOSE ?=
test: env-guard ## Backend tests (no coverage; one line on success)
	uv run python scripts/pytest_quiet.py $(if $(PYTEST_VERBOSE),--verbose,) -m "not slow" -n $(PYTEST_JOBS)

cov: env-guard ## Backend tests + coverage gate (same scope as CI, cndb package only; threshold in pyproject [tool.coverage.report])
	uv run pytest -m "not slow" --cov=$(PACKAGE) --cov-report=term --cov-report=html -n $(PYTEST_JOBS)
	@echo 'Coverage report: htmlcov/index.html'

gitkeep-check: ## Verify key .gitkeep files (missing ones break CI / packaging)
	uv run python scripts/check_gitkeep.py

adr-check: ## Verify ADR landing status, handoff sections and CHANGELOG references
	uv run python scripts/check_adr_landing.py
	uv run python scripts/adr_index.py --check

adr-index: ## Regenerate docs/adr/INDEX.md (one line per ADR, for context-budgeted agents)
	uv run python scripts/adr_index.py

context-split: ## Regenerate docs/context/*.md glossary shards from CONTEXT.md (generated, never hand-edited)
	uv run python scripts/context_split.py

constraint-check: ## Verify hard-constraint ledger format, unique ids, source ADR and make targets (ADR 0119)
	uv run python scripts/check_constraints.py

# 超长文件清单：按需生成，**不落盘成文档**。曾手工维护在 .agents/backlog.md，
# 实测 2026-11-05 的快照到 2026-11-30 已全面失真（后端 4/5 抽查行数偏差 2%~57%，
# 前端 37 条路径全部缺 `frontend/` 前缀），所以清单删除、改为现算。
MIN ?= 500
long-files: ## List source files above MIN lines (default 500; backend + frontend)
	uv run python scripts/long_files.py --min $(MIN)

# ── 上下文取用：按关键词取，不整读 ──────────────────────────────────────
# 这三个目标替代「把大文件整读进上下文」的动作。实测收益：
#   CONTEXT.md        76 KB → make context GREP=白板        ≈ 2 KB
#   CONSTRAINTS.md    16 KB → make constraints GREP=H31     ≈ 0.3 KB
#   docs/adr/*.md  200–400 行 → make adr 0203               ≈ 8.6 KB（--full 才是全文）
context: ## Print only glossary rows matching GREP (replaces reading CONTEXT.md)
	uv run python scripts/context_split.py --grep "$(GREP)"

constraints: ## Print only ledger rows matching GREP, e.g. GREP=H31 (replaces reading CONSTRAINTS.md)
	uv run python scripts/check_constraints.py --grep "$(GREP)"

adr: ## Print one ADR's status / 落地状态 / 交接 / 不变量 (N=0203; FULL=1 or BRIEF=1)
	uv run python scripts/adr_show.py $(N) $(if $(FULL),--full,) $(if $(BRIEF),--brief,)

# 回填 CHANGELOG 但不读它：文件约 1.1 MB，单条条目 2–7 KB，头部 20 行就 44 KB。
# 「更新 CHANGELOG」若让 agent 整读，每轮白烧 ~1.1 MB 上下文；本目标只报插入行号与增量。
# 用法：printf '%s\n' '- **【域】标题（S0）**：说明。' | make changelog-add
#      make changelog-add FILE=/tmp/entry.md SECTION=feature
SECTION ?= fix
changelog-add: ## Append one CHANGELOG entry without reading the file (FILE= or stdin; SECTION= default 修复)
	@uv run python scripts/changelog_add.py $(if $(FILE),--file $(FILE),) --section $(SECTION)

# F0 in one process (requirement 0207 / ADR 0181): the six static checks used to be six separate
# `uv run` invocations (~0.4s startup each on Windows, 40% of the budget) printing 110+ lines.
# scripts/gates.py imports the governance scripts, calls ruff / pyrefly directly, skips the
# frontend chain unless `frontend/**` changed, prints one line on success and records timings.
GATE_ARGS ?=
check-fast: env-guard ## F0 gate: static checks in one process, path aware, one line of output (budget <=2s)
	uv run python scripts/gates.py $(GATE_ARGS)

gate-report: ## Show F0 gate timings trend (p50 / p90 over the last 30 runs)
	uv run python scripts/gate_report.py

# Open a work round: environment + dirty tree + last round's failures + the F0 gates, in one
# process and under two seconds. Catches a red baseline before any edit (requirement 0207 C3).
preflight: ## Start-of-round check: env, dirty tree, last failures, F0 gates (budget <=2s)
	uv run python scripts/preflight.py

# Inner-loop coverage: only the files this change touched must reach 95%. Same threshold and
# same line/branch/exclude rules as [tool.coverage.report]; the full `make cov` fail_under gate is
# untouched (H10) and still runs in CI / at phase wrap-up (requirement 0207 C1).
cov-changed: env-guard ## Inner loop: coverage gate on the changed source files only (budget <=60s)
	@uv run python scripts/cov_changed.py --base $(BASE)

e2e: frontend-build ## Frontend E2E (Playwright; webServer boots an isolated backend, run npx playwright install chromium first)
	cd frontend && pnpm e2e

e2e-dev: $(FRONTEND_DEPS) ## E2E in dev mode (Vite dev serves sources; catches regressions only visible in dev)
	cd frontend && pnpm e2e:dev

e2e-affected: frontend-build ## Targeted E2E: select affected specs from git changes (E2E_BASE_REF defaults to HEAD~1, untracked specs count too)
	cd frontend && pnpm e2e:affected

# Reuse an already seeded isolated server for E2E (requirement 0181 C6): saves the fixed cost of
# rmtree + seed + server boot on every round. Local inner loop only — the default path still
# rebuilds every time, so no one reuses a server of unknown origin.
E2E_REUSE_PORT ?= 8001
e2e-reuse: frontend-build ## E2E against an already seeded server (a single spec, e.g. make e2e-reuse SPEC=tests/e2e/critical/navigation.spec.ts)
	cd frontend && CNDB_E2E_REUSE=1 E2E_PORT=$(E2E_REUSE_PORT) pnpm e2e $(SPEC)

# Benchmark import row count: override with make bench ROWS=100000
ROWS ?= 10000

bench: env-guard ## Benchmark (10k-row import + query throughput on a temporary SQLite DB; make bench ROWS=100000 to scale)
	uv run python scripts/bench_10k_rows.py --rows $(ROWS)

# L1 config changes / L0 documentation changes: governance checks only (no code, no tests)
check-docs: env-guard ## Documentation gate (use when only *.md changed)
	uv run python scripts/gates.py --no-frontend --only-governance
# L2 code changes: lightweight static gates + full backend suite (requirement 0181 four-level funnel, L2)
flow: check-fast test ## L2 gate: lightweight static checks + full backend suite (budget <=3min)

# L1 targeted verification (requirement 0181 C2): run only the tests related to the git change,
# typically 20-40s for a single module. Shared infrastructure / too-wide hits fall back to the
# full suite — slower is better than missing. BASE can point at a remote branch.
BASE ?= HEAD
verify-changed: env-guard ## L1 gate: targeted verification, only tests related to the git change (BASE=origin/main compares against a remote branch; budget <=60s)
	@uv run python scripts/verify_changed.py --base $(BASE)

verify-changed-plan: ## Only print the verify-changed plan, run no tests
	@uv run python scripts/verify_changed.py --base $(BASE) --dry-run

retest: env-guard ## Re-run only last round's failures (falls back to the full suite explicitly when lastfailed is empty)
	@uv run python scripts/retest.py $(PYTEST_EXTRA)

check-backend: env-guard ## Backend gate (cov + lint + types + gitkeep + ADR; PYTEST_JOBS tunable)
	@$(MAKE) --no-print-directory -j1 cov gitkeep-check adr-check lint typecheck

check-frontend: $(FRONTEND_DEPS) ## Frontend gate (vitest coverage + patch + tsc + eslint; VITEST_MAX_WORKERS tunable)
	@$(MAKE) --no-print-directory -j1 frontend-coverage frontend-static

# Backend and frontend run serially: vitest jsdom cases next to pytest -n 16 oversubscribe the
# CPU and the RTL findBy* default 1s wait times out under the congestion; the semantics are
# still "one command runs every gate".
check: env-guard $(FRONTEND_DEPS) ## Full gate (backend -> frontend serially, each phase owning the CPU)
	@$(MAKE) --no-print-directory check-backend
	@$(MAKE) --no-print-directory check-frontend

# ── Build / package / release ─────────────────────────────────────────

build: frontend-build ## Build release artifacts (frontend -> wheel + sdist)
	uv build

# ── Docker / offline deployment ───────────────────────────────────────

# Version (defaults to pyproject.toml; override with make docker-build VERSION=x.y.z)
VERSION ?= $(shell grep -m1 -E '^version' pyproject.toml | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')

docker-dev dd: ## Docker dev mode: backend + frontend in containers (CNDB_SOURCES=auto defaults to cn locally; frontend 5173 / backend 8772)
	bash deploy/docker-sources.sh exec docker compose -f docker-compose.dev.yml up --build

docker-dev-down ddd: ## Stop Docker dev mode (removes containers and network, keeps data volumes)
	docker compose -f docker-compose.dev.yml down

docker-stop ds: ## Quickly stop Docker dev mode (stops containers only, keeps them and the data volumes)
	docker compose -f docker-compose.dev.yml stop

docker-build db: build ## Build the image locally (CNDB_SOURCES=auto defaults to cn, GitHub uses global)
	bash deploy/build-image.sh $(VERSION)

docker-export de: ## Export the offline delivery bundle (run make docker-build first; CNDB_SOURCES only affects the nginx image source)
	bash deploy/export-image.sh $(VERSION)

clean: ## Remove build artifacts and caches
	@uv run python scripts/clean.py

BUMP_PART := $(filter-out bump,$(MAKECMDGOALS))

bump: ## Bump the version (patch by default, usage: make bump [minor|major])
	@uvx $(UVX_INDEX) bump-my-version bump $(if $(BUMP_PART),$(firstword $(BUMP_PART)),patch) --tag

patch minor major:
	@:

pub: ## Upload dist/ to PyPI (run make build first)
	uvx $(UVX_INDEX) twine upload dist/*.whl dist/*.tar.gz

push: ## Push the current branch to every remote (tags included)
	@uv run python scripts/push.py

pack-doctor: ## fspack environment diagnostics (checks packaging toolchain availability)
	uv run fspack doctor

pack: frontend-build ## Package for the current platform (fspack build + package + smoke test)
	uv run fspack b .
	uv run fspack p . --format all --no-build
	@uv run python -c "import subprocess, sys; sys.exit(subprocess.run(['dist/cndb.exe' if sys.platform == 'win32' else 'dist/cndb', 'info']).returncode)"

pack-cache-clean: ## Clean the fspack cache (wheels + nuitka)
	uv run fspack cache clean

# ── Ops / maintenance (requirement 0205) ──────────────────────────────

ops: ## List every maintenance task (stage / name / destructive / opt-in)
	uv run cndb ops list

ops-check: ## Read-only health inspection of the whole install (exit 1 when issues are found)
	uv run cndb ops check --fail-on issues

ops-maintain: ## One-shot maintenance: check -> repair; clean stays dry-run (cron-friendly)
	uv run cndb ops all --fail-on issues

ops-apply: ## Same as ops-maintain but really deletes garbage (destructive; asks in a TTY)
	uv run cndb ops all --apply --yes
