# SPDX-FileCopyrightText: 2026 Science Against Authoritarianism Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Local gate for the Pharos quantitative pillar. Stdlib only — no pip install.
.PHONY: help clean lint test indicators divergence capture vdem-pillars wealth-power sequence opacity-crime typology planet flourish coop science resilience panel-causality comebacks forecast forecast-v2 forecast-v3 forecast-v4 auto-cycle sims validate staleness overstatement counts threat-model metadata index links sync security opsec reasoning grader-pack interop release-bundle pharos pipeline-offline audit-json site-build site-verify site-test dashboard hooks snapshot verify-offline verify

# Make the `pharos` package importable from the repo root without install or sys.path hacks.
export PYTHONPATH := src$(if $(PYTHONPATH),:$(PYTHONPATH),)

help:        ## show this help
	@grep -E '^[a-zA-Z_-]+:.*## ' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "  %-16s %s\n", $$1, $$2}'

clean:       ## remove Python build artifacts
	find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
	find . -type f -name '*.pyc' -delete 2>/dev/null || true

lint:        ## syntax-check & zero-dependency AST hygiene audit across all Python files; run ruff if installed
	@python3 -m compileall -q src/pharos tests pharos || { echo "lint: syntax error"; exit 1; }
	@python3 -m pharos.lint_ast
	@if command -v ruff >/dev/null 2>&1; then \
		echo "lint: running ruff"; \
		ruff check src/pharos tests; \
	fi

test:        ## run offline unit tests (calculations + simulator validation + ledger gates)
	python3 -m unittest discover -s tests -p "test_*.py" -v

indicators:  ## fetch WGI (6 dimensions) + (re)compute the open indicators with uncertainty (LIVE)
	python3 -m pharos.indicators.wgi_governance

divergence:  ## triangulate WGI V&A × V-Dem × Freedom House — publish divergence, not a single score (LIVE)
	python3 -m pharos.indicators.voice_divergence

capture:     ## cross-pillar institutional-capture coupling (VA vs RL/CC/RQ/GE/PV, offline from committed CSVs)
	python3 -m pharos.indicators.institutional_capture

vdem-pillars: ## cross-dataset V-Dem Academic Freedom, Political Corruption & Rule of Law coupling (offline from snapshots)
	SAA_OFFLINE=1 python3 -m pharos.indicators.vdem_capture_pillars

wealth-power: ## WID Top-1% Wealth Share & V-Dem Judicial/Civil-Society coupling (offline from snapshots)
	SAA_OFFLINE=1 python3 -m pharos.indicators.wealth_power_coupling

sequence:    ## 2000-2024 8-pillar erosion & reversal sequence event study, placebo check & country trajectories (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.erosion_sequence

opacity-crime: ## media capture, beneficial ownership opacity, GI-TOC vs UNODC crime & GDP controls (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.opacity_crime_coupling

typology:    ## Stage 10 planetary 237-polity continent synthesis & 6-category structural typology (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.regime_typology

planet:      ## Stage 11 whole-planet life expectancy, clean electricity, forest cover & CO2 coupling (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.planetary_wellbeing

flourish:    ## Stage 12 whole-world child survival, armed conflict, protected land, schooling & 10-yr panel tests (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.global_flourishing

coop:        ## Stage 13 whole-world cooperation foundations: social trust, Gini, women's empowerment & internet access (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.cooperation_foundations

science:     ## Stage 14 whole-world science, R&D, researchers, articles & DTP3 immunization capacity (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.science_capacity

resilience:  ## Stage 16 cross-pillar causal-sensitivity, 500-draw bootstrap 95% CI, 6-continent LOCO & Non-Western tests (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.resilience_synthesis

panel-causality: ## Stage 17 Two-Way Fixed-Effects (Country+Year FE) panel causality, clustered bootstrap, placebo & Cinelli-Hazlett RV (offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.panel_causality

comebacks:   ## Stage 19 Democratic Comebacks vs. Autocratization Lock-In (2000-2024, GDP & Non-Western permutation tests, offline)
	SAA_OFFLINE=1 python3 -m pharos.indicators.comeback_mechanisms

forecast:    ## pharos-forecast v1 — corrective backsliding backtest, CRPS/Brier + calibration vs two baselines (LIVE)
	python3 -m pharos.forecast.pharos_forecast

forecast-v2: ## pharos-forecast v2 — origin-safe 8-pillar multi-horizon backtest (h=3,5,7yr, offline)
	SAA_OFFLINE=1 python3 -m pharos.forecast.pharos_forecast_v2

forecast-v3: ## pharos-forecast v3 — recency-weighted, OOF-calibrated & conformal backtest + lead-lag (offline)
	SAA_OFFLINE=1 python3 -m pharos.forecast.pharos_forecast_v3

forecast-v4: ## Stage 18 pharos-forecast v4 — autonomous Online Hedge meta-ensemble, boosted stumps & Mondrian conformal (offline)
	SAA_OFFLINE=1 python3 -m pharos.forecast.pharos_forecast_v4

auto-cycle:  ## run 5-stage autonomous zero-leak research, calibration & OPSEC closed-loop cycle
	python3 -m pharos.autonomous_loop --write

snapshot:    ## refresh the pinned inputs from live sources, then regenerate derived offline (the deliberate pin step)
	python3 -m pharos.indicators.wgi_governance --snapshot
	python3 -m pharos.indicators.voice_divergence --snapshot
	python3 -m pharos.indicators.vdem_capture_pillars --snapshot
	python3 -m pharos.indicators.wealth_power_coupling --snapshot
	python3 -m pharos.indicators.erosion_sequence --snapshot
	python3 -m pharos.indicators.planetary_wellbeing --snapshot
	python3 -m pharos.indicators.global_flourishing --snapshot
	python3 -m pharos.indicators.cooperation_foundations --snapshot
	python3 -m pharos.indicators.science_capacity --snapshot
	python3 -m pharos.forecast.pharos_forecast --snapshot
	python3 -m pharos.snapshot_manifest --write
	python3 -m pharos.pipeline
	@echo "snapshot: refreshed — review 'git diff', then commit data/snapshots + data/derived"

pipeline-offline: ## run all quantitative pipeline stages deterministically from pinned snapshots
	python3 -m pharos.pipeline

verify-offline: ## deterministic gate, NO network — recompute from pinned snapshots; must match committed derived
	python3 -m pharos.snapshot_manifest
	python3 -m pharos.pipeline
	@if git rev-parse --git-dir >/dev/null 2>&1; then \
		git diff --quiet -- data/derived || { echo "DRIFT: offline recompute changed data/derived — run 'make snapshot' and commit"; git --no-pager diff --stat -- data/derived; exit 1; }; \
	else \
		echo "warn: not a git repo — skipping git drift check"; \
	fi
	python3 -m pharos.parallel_tests
	python3 -m pharos.ledger_validate
	python3 -m pharos.ledger_staleness
	python3 -m pharos.audit_overstatement
	python3 -m pharos.audit_counts
	python3 -m pharos.audit_threat_model
	python3 -m pharos.audit_metadata
	python3 -m pharos.ledger_digest
	python3 -m pharos.audit_links
	python3 -m pharos.audit_sync
	python3 -m pharos.audit_security
	python3 -m pharos.audit_reasoning
	@if command -v node >/dev/null 2>&1; then \
		node --test site/tests/*.test.js; \
	fi
	@echo "verify-offline: ok"

sims:        ## run the Tier-1 validated mechanism simulators (demos)
	python3 -m pharos.sims.sim_threshold_cascade
	python3 -m pharos.sims.sim_network_cascade
	python3 -m pharos.sims.sim_committed_minority
	python3 -m pharos.sims.sim_reverse_dominance
	python3 -m pharos.sims.sim_complex_contagion
	python3 -m pharos.sims.sim_civil_violence
	python3 -m pharos.sims.sim_opinion_dynamics
	python3 -m pharos.sims.sim_institutional_capture
	python3 -m pharos.sims.sim_commons_cooperation
	python3 -m pharos.sims.sim_cooperation_dilemmas
	python3 -m pharos.sims.sim_coupled_society

validate:    ## structural gate: every ledger entry conforms to the grading protocol + agrees with index.json
	python3 -m pharos.ledger_validate

staleness:   ## freshness gate: fail if any ledger entry is past its review interval (is the light lit, or stale?)
	python3 -m pharos.ledger_staleness

overstatement: ## honesty gate: fail if graded prose makes an unconditional claim the evidence can't carry
	python3 -m pharos.audit_overstatement

counts:      ## consistency gate: fail if headline counts (entries/grades/tests) OR the site's computed figures drift from the data
	python3 -m pharos.audit_counts

threat-model: ## covenant gate: fail if any published data file drops below country/institution level (watch power, not people)
	python3 -m pharos.audit_threat_model

metadata:    ## covenant gate: fail if any derived output lacks HDX-tier / inversion-red-team sidecar metadata
	python3 -m pharos.audit_metadata

index:       ## (re)generate the human ledger index + falsification watch (ledger/INDEX.md) from the entries
	python3 -m pharos.ledger_digest --write

links:       ## internal link integrity gate: verify every relative file link across docs, ledger, and site
	python3 -m pharos.audit_links

sync:        ## cross-surface sync & REUSE.toml audit (Audit #10)
	python3 -m pharos.audit_sync

security:    ## security headers, transport, CSP, sink & secret hygiene audit (Audit #11)
	python3 -m pharos.audit_security

opsec:       ## operational security, visitor privacy, tarball anonymity & personal/company isolation audit
	python3 -m pharos.opsec

reasoning:   ## formal epistemic reasoning graph & falsification audit (Audit #12)
	python3 -m pharos.audit_reasoning

grader-pack: ## generate a blind, grade-stripped second-grader review packet
	python3 -m pharos.grader_pack

interop:     ## regenerate Frictionless datapackage.json, static API v1, Atom feed & PARTNER_INSTITUTIONS.md
	python3 -m pharos.partners --write-doc
	python3 -m pharos.interop_bundle

release-bundle: ## build deterministic, history-free anonymous offline source tarball + blind grader kit + SHA256SUMS.txt
	python3 -m pharos.release_bundle --out-dir site/dist/downloads

site-test:   ## run offline Node native tests for frontend pure modules
	node --test site/tests/*.test.js

pharos:      ## the project as one command — e.g. `make pharos ARGS="ledger --grade ROBUST"` or `./pharos country HUN`
	python3 -m pharos.cli $(ARGS)

dashboard:   ## one GREEN/RED report across every offline audit (12 gates)
	python3 -m pharos.audit_dashboard

audit-json:  ## emit machine-readable JSON audit + manifest telemetry report
	python3 -m pharos.cli audit-report --json

site-build:  ## build the static Pharos Vite portal bundle locally
	npm --prefix site run build

site-verify: ## build and smoke-verify standalone site/dist/ bundle + anonymous verification tarball
	npm --prefix site run build
	python3 -m pharos.release_bundle --out-dir site/dist/downloads
	@python3 -c "import os, re, sys; d='site/dist'; req=['index.html','404.html','portal_i18n.js','_worker.js','_routes.json','learn.html','learn.js','universities.html','universities.css','universities.js','press.html','press.js','embed.html','embed.js','favicon.svg','og-card.png','sitemap.xml','manifest.webmanifest','sw.js','_headers','_redirects','.well-known/security.txt','robots.txt','SECURITY.md','THREAT_MODEL.md','CITATION.cff','datapackage.json','croissant.json','feed.xml','api/v1/observatory.json','api/v1/bootstrap.json','api/v1/polities.json','api/v1/polity/BRA.json','docs/partners.json','docs/global_sources.json','docs/PARTNER_INSTITUTIONS.md','docs/COOPERATION_PROBLEMS_AND_SOLUTIONS.md','docs/GUIDE_FOR_EVERYONE.md','docs/CLASSROOM_AND_FAMILY_KIT.md','docs/indicators/planetary-wellbeing.md','docs/indicators/global-flourishing.md','docs/indicators/cooperation-foundations.md','docs/indicators/science-capacity.md','data/snapshots/manifest.json','data/derived/regime_typology.json','data/derived/regime_typology.csv','data/derived/planetary_wellbeing.json','data/derived/planetary_wellbeing.csv','data/derived/global_flourishing.json','data/derived/global_flourishing.csv','data/derived/cooperation_foundations.json','data/derived/cooperation_foundations.csv','data/derived/science_capacity.json','data/derived/science_capacity.csv','data/derived/resilience_sensitivity.json','data/derived/resilience_sensitivity.csv','data/derived/panel_causality.json','data/derived/panel_causality.csv','data/derived/comeback_mechanisms.json','data/derived/comeback_mechanisms.csv','data/derived/forecast_v3_calibrated.json','data/derived/forecast_v3_calibrated.csv','data/derived/forecast_v4_adaptive.json','data/derived/forecast_v4_adaptive.csv','data/derived/autonomous_cycle_status.json','data/derived/prospective_forecast_lock.json','data/derived/bias_audit.json','data/derived/global_literature_pulse.json','data/derived/coupled_society_phase.json','ledger/catalog.json','ledger/index.json','ledger/INDEX.md','ledger/reasoning_graph.json','src/pharos/sims/sim_institutional_capture.py','src/pharos/sims/sim_commons_cooperation.py','src/pharos/sims/sim_cooperation_dilemmas.py','src/pharos/sims/sim_coupled_society.py','downloads/pharos-v0.4.0-source.tar.gz','downloads/pharos-blind-grader-pack.tar.gz','downloads/SHA256SUMS.txt','downloads/manifest.json']; forbid=['STATUS.md','docs/CHRONICLE.md','docs/RFC_PARTNERSHIPS.md']; miss=[p for p in req if not os.path.isfile(os.path.join(d,p))]; leaked=[p for p in forbid if os.path.exists(os.path.join(d,p))]; html=open(os.path.join(d,'index.html'),encoding='utf-8').read(); errs=[]; \
	errs += [f'missing staged file: {p}' for p in miss]; \
	errs += [f'internal file leaked into site/dist: {p}' for p in leaked]; \
	errs += ['parent-escaping href=\"../\" left in dist/index.html'] if 'href=\"../' in html else []; \
	errs += ['external http/https script/img in dist/index.html'] if re.search(r'<(?:script|img|iframe)[^>]+src=\"https?://', html, re.I) else []; \
	errs += ['external non-canonical <link> in dist/index.html'] if any('rel=\"canonical\"' not in m.group(0).lower() for m in re.finditer(r'<link[^>]+href=\"https?://[^>]*>', html, re.I)) else []; \
	chunks=os.listdir(os.path.join(d,'assets')); \
	errs += ['expected split chart-vendor chunk'] if not any(c.startswith('chart-vendor') for c in chunks) else []; \
	errs += ['expected split world-geo chunk'] if not any(c.startswith('world-geo') for c in chunks) else []; \
	errs += ['expected split i18n-edu chunk'] if not any(c.startswith('i18n-edu') for c in chunks) else []; \
	print('\n'.join('  ✗ ' + e for e in errs)) if errs else print(f'site-verify: ok ({len(req)} required artifacts, {len(forbid)} internal logs excluded, {len(chunks)} split asset chunks, zero ../ or 3rd-party/identity leaks)'); \
	sys.exit(1 if errs else 0)"

hooks:       ## install the FREE local git hooks (pre-commit -> dashboard, pre-push -> verify-offline). No cloud, no billing.
	chmod +x .githooks/pre-commit .githooks/pre-push
	git config core.hooksPath .githooks
	@echo "hooks: installed — pre-commit runs 'make dashboard', pre-push runs 'make verify-offline' (bypass with --no-verify)"

verify:       ## LIVE release-candidate gate: recompute first, then audit the outputs that would ship
	$(MAKE) indicators
	$(MAKE) divergence
	$(MAKE) capture
	$(MAKE) vdem-pillars
	$(MAKE) wealth-power
	$(MAKE) sequence
	$(MAKE) opacity-crime
	$(MAKE) typology
	$(MAKE) planet
	$(MAKE) flourish
	$(MAKE) coop
	$(MAKE) science
	$(MAKE) forecast
	$(MAKE) forecast-v2
	$(MAKE) dashboard
	@echo "verify: ok"
