🎯 COMPLETE PACKAGE GUIDE - Use in Cursor Code

You can work from a git clone (recommended) or from an early-warning-system.zip extract. Both contain the same application tree under early-warning-system/.

Public repository: https://github.com/mamta2009/aqinepal2026
Technical truth (API resolver, env vars, provenance/A2A, notifications, admin APIs): early-warning-system/docs/guides/IMPLEMENTATION_SNAPSHOT.md β€” update it when wiring integrations.


πŸ“¦ What's in early-warning-system/

early-warning-system/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ main.py                 ← FastAPI app; mounts /frontend, landing pages, /guides, /admin/dashboard
β”‚   β”œβ”€β”€ admin_panel.py          ← Operator JSON APIs under /api/admin/*
β”‚   β”œβ”€β”€ cities_config.py        ← CITIES_CONFIG (demo municipalities; AQ + registration)
β”‚   β”œβ”€β”€ notification_auth.py    ← NOTIFICATION_API_KEY + Twilio webhook signature helpers
β”‚   β”œβ”€β”€ notifications_api.py    ← Registration, broadcast, evaluate, webhooks, analytics
β”‚   β”œβ”€β”€ twilio_notify.py        ← SMS / WhatsApp via Twilio
β”‚   β”œβ”€β”€ db_state.py             ← Shared MongoDB handle
β”‚   β”œβ”€β”€ requirements.txt
β”‚   └── .env.example            ← Primary template; copy to backend/.env
β”œβ”€β”€ landing/
β”‚   β”œβ”€β”€ landing.html            ← GET /  (marketing landing)
β”‚   β”œβ”€β”€ guides.html       ← GET /guides (diagrams hub; not full docs/ tree)
β”‚   β”œβ”€β”€ registration_portal.html ← GET /registration
β”‚   β”œβ”€β”€ admin_dashboard.html     ← GET /admin/dashboard (operator console; API key + PIN)
β”‚   └── assets/
β”œβ”€β”€ frontend/
β”‚   └── index.html              ← Dashboard at /frontend/index.html
β”œβ”€β”€ config/
β”‚   └── .env.example            ← Optional second file; fills only unset vars after backend/.env
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ guides/
β”‚   β”‚   β”œβ”€β”€ IMPLEMENTATION_SNAPSHOT.md
β”‚   β”‚   β”œβ”€β”€ CURSOR_SETUP_GUIDE.md …
β”‚   β”‚   └── blockchain-ai/ …
β”‚   β”œβ”€β”€ tech/                   ← Diagrams surfaced on /guides/media/tech/…
β”‚   └── blockchain-ai/          ← Reference `.py` only (Markdown β†’ `docs/guides/blockchain-ai/`)
β”œβ”€β”€ docs-private/               ← Internal drafts β€” operator-only Markdown preview in `/admin/dashboard`
β”œβ”€β”€ README.md
└── .gitignore

πŸš€ OPEN IN CURSOR (2 minutes)

Step 1a: Clone from GitHub (recommended)

git clone https://github.com/mamta2009/aqinepal2026.git
cd aqinepal2026/early-warning-system   # or open repo root and cd into early-warning-system/

Step 1b: Or extract ZIP

unzip early-warning-system.zip
cd early-warning-system

Step 2: Open in Cursor

cursor .
# File β†’ Open Folder β†’ select the folder that contains backend/ and landing/

Step 3: Cursor sees (typical)

πŸ“ early-warning-system
  πŸ“ backend
    πŸ“„ main.py, admin_panel.py, notifications_api.py …
    πŸ“„ requirements.txt, .env.example
  πŸ“ landing
    πŸ“„ landing.html, guides.html, registration_portal.html, admin_dashboard.html
  πŸ“ frontend
    πŸ“„ index.html
  πŸ“ config
    πŸ“„ .env.example
  πŸ“ docs …
  πŸ“„ README.md

⚑ QUICK START IN CURSOR

1. Open Terminal in Cursor

Cursor Menu β†’ Terminal β†’ New Terminal

2. Install Dependencies

cd backend
python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -r requirements.txt

Use Python 3.10+ (3.12 OK). If pip install fails, upgrade pip: pip install -U pip.

Important: requirements.txt lives in early-warning-system/backend/, not the repo root. If you run pip install -r requirements.txt from Project_1_aqi/ you will get β€œfile not found.” Prefer the project venv (backend/.venv) so other global packages (for example google-genai) do not conflict with pinned versions.

After install, keep using the same interpreter for the API: backend/.venv/bin/python or activate the venv before uvicorn.

3. Setup Environment

cd ../backend
cp .env.example .env
# Edit .env with your keys. Optional: also copy ../config/.env.example β†’ ../config/.env
# (backend/.env loads first; config/.env fills only unset variables.)

Template files: backend/.env.example (backend-centric keys + notifications security/automation) and config/.env.example (broader integration list). Keep them in sync with docs/guides/IMPLEMENTATION_SNAPSHOT.md when adding env vars.

Blockchain (optional but real):

Notifications (optional; needs MongoDB for persistence):

Quick URLs (same origin as API): http://127.0.0.1:8000/frontend/index.html, http://127.0.0.1:8000/registration (β†’ POST /api/contacts/register), http://127.0.0.1:8000/guides, http://127.0.0.1:8000/admin/dashboard. See Notifications below for API routes.

4. Run Backend

cd ../backend
source .venv/bin/activate   # if not already

# Recommended (explicit host; avoids blank page if you paste 0.0.0.0 into the browser)
python -m uvicorn main:app --reload --host 127.0.0.1 --port 8000

# Or: python main.py  (if your tree still wires this to uvicorn)

The server serves the API and static mounts. Use http://127.0.0.1:8000 (or http://localhost:8000) in the browser β€” http://0.0.0.0:8000 often shows a blank page.

5. Open the app (same origin)

What URL
Marketing landing http://127.0.0.1:8000/
Guides hub http://127.0.0.1:8000/guides
Registration http://127.0.0.1:8000/registration
Data dashboard http://127.0.0.1:8000/frontend/index.html
Operator admin http://127.0.0.1:8000/admin/dashboard (needs NOTIFICATION_API_KEY + PIN; see docs/guides/IMPLEMENTATION_SNAPSHOT.md β†’ Operator admin)
OpenAPI http://127.0.0.1:8000/docs
Route map http://127.0.0.1:8000/api/system-discovery

Opening frontend/index.html as file:// may still call the API if the dashboard falls back to localhost:8000 β€” prefer URLs above.


πŸ“ FILE-BY-FILE BREAKDOWN

backend/main.py

# FastAPI application with:
βœ… Health check + case endpoints
βœ… Realistic WHO-pattern case generator
βœ… Static mount: /frontend β†’ ../frontend (dashboard URL below)
βœ… blockchain_integration.py β€” SHA-256 payload anchoring + optional EIP-191 signing
βœ… GET /api/blockchain/status β€” Polygon RPC ping (read-only, no transactions)
βœ… MongoDB for persistence when MONGODB_URL is set (daily reports + notification registry DB)
βœ… notifications_api router β€” registration, broadcast, analytics, Twilio webhooks (see below)

# Run:
python -m uvicorn main:app --reload --host 127.0.0.1 --port 8000
# β†’ http://127.0.0.1:8000  (API + /frontend + landing + /guides + /admin/dashboard)

Notifications stack (notifications_api.py, twilio_notify.py, db_state.py)

When MONGODB_URL is configured, startup ensures indexes for contact registration and notification logs. Twilio and Resend are optional; configure only the channels you use.

Diagram (code-aligned): early-warning-system/docs/tech/NOTIFICATION_FLOW_DIAGRAM.svg — also embedded on /guides (Notification & alert flow). Evaluate: POST /api/alerts/evaluate pulls live AQ for a CITIES_CONFIG city and broadcasts when min_level and cooldown allow (cron-friendly). Alternate: your job may call /api/air-quality/current and then POST /api/alerts/broadcast. Daily cases: optional spike→broadcast after POST /api/health/cases/daily-report when daily surge env vars are enabled (see Notifications env bullets).

Representative routes (when NOTIFICATION_API_KEY is set, routes marked πŸ”’ require Bearer or X-API-Key):

Purpose Method / path
Registration UI GET /registration
Register contact POST /api/contacts/register
Verify code POST /api/contacts/verify
List / get / update contacts πŸ”’ GET /api/contacts, πŸ”’ GET /api/contacts/{id}, πŸ”’ PUT /api/contacts/{id}/preferences
Send to one contact πŸ”’ POST /api/notifications/send
Broadcast alert πŸ”’ POST /api/alerts/broadcast
Evaluate AQ β†’ broadcast πŸ”’ POST /api/alerts/evaluate (body: city, optional recipient_type, filter_city, min_level, force)
Twilio test πŸ”’ POST /api/notifications/twilio/test (body may include channel: sms or whatsapp)
WhatsApp sandbox help GET /api/notifications/whatsapp/sandbox-info
Inbound / status webhooks POST /api/webhooks/sms, POST /api/webhooks/whatsapp, POST /api/webhooks/message-status
Analytics πŸ”’ GET /api/analytics/notifications, πŸ”’ GET /api/analytics/contacts

GET /api/health includes notification_registry: true when the full Mongo database handle is active. GET /api/runtime-config includes integrations.resend_configured and existing integration flags.

Point Twilio webhook URLs at your public API host + these paths when testing inbound SMS/WhatsApp from a tunnel (for example ngrok).

backend/blockchain_integration.py

# Used by main.py:
βœ… Canonical JSON β†’ SHA-256 content hash on case payloads
βœ… Optional signature if POLYGON_PRIVATE_KEY is configured
βœ… Optional Web3 RPC ping (POLYGON_RPC_URL)
# On-chain contract anchoring is a separate step when you deploy a contract.

frontend/index.html

<!-- Dashboard:
βœ… API_BASE from GET /api/runtime-config (PUBLIC_API_ORIGIN / API_PATH_PREFIX when set)
βœ… Header links: /registration (Register for alerts), /guides
βœ… Weekly respiratory bar chart: GET /api/cases/week/{city}
βœ… Footer Chain line from GET /api/blockchain/status + last payload verification
βœ… AQ card + compare: GET /api/air-quality/current (server resolver: WeatherAPI β†’ WAQI β†’ Rapid)
βœ… provenance on JSON: deployment_role + confidence tier for tooling / agents

If you deploy elsewhere, open via that host so runtime-config resolves correctly.

config/.env.example

Copy to config/.env. Key integrations (see docs/guides/IMPLEMENTATION_SNAPSHOT.md for full resolver order):

- WEATHERAPI_COM_API_KEY β€” direct WeatherAPI.com (preferred for AQ + /api/weather/current)
- WAQI_TOKEN β€” WAQI / aqicn (AQ fallback)
- RAPIDAPI_WEATHER_* β€” Rapid marketplace weather/air fallback + related products
- OPENWEATHER_API_KEY β€” supplementary OWM routes only (/api/weather/openweather/…)
- OPENROUTER_API_KEY β€” POST /api/ai/openrouter
- DEPLOYMENT_MODE β€” REGIONAL default (surfaced in API payloads)
- MONGODB_URL β€” required for persisted daily reports and the notification registry (contacts, logs, broadcasts, alert_evaluation_cooldown)
- TWILIO_* / RESEND_* β€” optional; see β€œNotifications” env bullets in Setup Environment above
- NOTIFICATION_API_KEY / TWILIO_WEBHOOK_* / ALERT_EVAL_* / DAILY_* β€” optional automation & security (see IMPLEMENTATION_SNAPSHOT.md Notifications section)
MongoDB/DHIS2/Polygon vars as documented in .env.example

README.md

Quick start instructions
Project structure
Next steps

See also: docs/guides/IMPLEMENTATION_SNAPSHOT.md (technical contract for demos)

πŸ”§ USING CURSOR'S FEATURES

Cursor Tools You'll Use:

1. Edit main.py
- Right-click β†’ "Edit with AI" to modify endpoints
- Ask: "Add MongoDB connection to main.py"
- Ask: "Add blockchain verification to health endpoints"

2. Edit index.html
- Right-click β†’ "Edit with AI" to modify dashboard
- Ask: "Connect dashboard to real API endpoints"
- Ask: "Add dark mode toggle"

3. Terminal
- Run: python main.py
- Test: curl http://localhost:8000/api/health

4. File Compare
- Right-click file β†’ "Compare with..." to see what changed


πŸ“Š TEST THE SYSTEM (5 minutes)

1. Start Backend

# In Cursor Terminal
python main.py

# Should see:
# INFO:     Uvicorn running on http://127.0.0.1:8000
# INFO:     Application startup complete

2. Test API Endpoints

# Open new terminal tab

# Health check
curl http://localhost:8000/api/health

# Get cases for Kathmandu
curl http://localhost:8000/api/cases/week/Kathmandu

# Get all cities
curl http://localhost:8000/api/cases/all-cities

# Blockchain / RPC + signing readiness
curl http://localhost:8000/api/blockchain/status

# Integration flags + AQ/weather posture (integrations.* on JSON)
curl http://localhost:8000/api/runtime-config

# Resolved air quality (shows source + provenance when keys are set)
curl "http://localhost:8000/api/air-quality/current?city=Kathmandu"

# All should return JSON when the backend is up and keys/quota permit upstream calls.

# Notifications (MongoDB must be configured for registry features)
curl http://localhost:8000/api/health   # check notification_registry + mongodb_persistence
curl http://localhost:8000/api/notifications/whatsapp/sandbox-info

3. Open Dashboard

Browser: http://localhost:8000/frontend/index.html

You should see:
- City selector (8 cities); cases chart filled from the API
- Footer: data status (cases + AQ source/confidence snippet) and blockchain / anchor line (expand tooltip for JSON)
- AQ from live resolver when configured (WeatherAPI-first); compare table staggers requests (~0.65s) to ease Rapid quota

βœ… SUCCESS CHECKLIST


🎯 NEXT STEPS IN CURSOR

Option 1: Deploy to Render (30 minutes)

The application source already lives at github.com/mamta2009/aqinepal2026. For a fresh machine: clone, set env on the host, deploy early-warning-system/backend with uvicorn (see render.yaml in the repo).

git clone https://github.com/mamta2009/aqinepal2026.git
cd aqinepal2026
# Configure Render (or another host) to run from early-warning-system with your .env secrets

Fork or create a private repo copy if you must not publish docs-private/ or other materials β€” then point Render at that remote instead.

Option 2: Modify & Enhance (1-2 hours)

In Cursor, ask AI to:
- "Add MongoDB integration to main.py"
- "Add real DHIS2 API connection"
- "Improve dashboard styling"
- "Add blockchain verification"
- "Add AI prediction models"
- "Wire automated alerts from air-quality thresholds to /api/alerts/broadcast"

Option 3: Add Real Data (Tomorrow)

Contact health ministry
Get real DHIS2 data
Update endpoint
Replace synthetic data

πŸ› οΈ CURSOR AI PROMPTS

For main.py:

"Add a new endpoint that integrates with MongoDB
to store respiratory case reports"

"Add blockchain verification to the health 
endpoints using the blockchain_integration module"

"Create an endpoint that pulls data from DHIS2
API and stores in MongoDB"

"After AQI exceeds a threshold, call POST /api/alerts/broadcast
with the right city and alert level"

For index.html:

"Update the API_BASE constant to use 
environment variables instead of hardcoding"

"Add a dark mode toggle to the settings panel"

"Improve the mobile responsiveness of the 
geographic selector"

For new files:

"Create a health_data_generator.py module with
realistic respiratory case patterns"

"Create a blockchain_integration.py module for
Polygon verification"

"Create an ai_models.py with respiratory 
case prediction models"

πŸ“ž TROUBLESHOOTING

Issue: "Module not found"

pip install -r requirements.txt

Issue: pkg_resources / web3 import error

# web3 6.x needs setuptools that still includes pkg_resources (<82)
pip install -r requirements.txt

Issue: "Port 8000 already in use"

# Use different port
python -m uvicorn main:app --reload --port 8001

Issue: "CORS error in dashboard"

Prefer http://127.0.0.1:8000/frontend/index.html (same origin = no CORS for API)
Opening from file:// may call http://localhost:8000 for API; ensure the backend is up and CORS middleware is on (it is)

Issue: "No data showing in charts"

Weekly case bars require a successful GET /api/cases/week/{city}
Open DevTools β†’ Network; fix CORS or wrong API host
Ensure you are not running two servers on port 8000

Issue: "Blockchain shows RPC offline"

Normal in restricted networks β€” anchoring (hash) still works; only the public RPC ping failed
Set POLYGON_RPC_URL to a reachable endpoint or ignore for local demos

Issue: Could not open requirements file

Run pip from early-warning-system/backend/ or pass the full path:
  pip install -r early-warning-system/backend/requirements.txt

Issue: pip β€œdependency conflicts” with google-genai / fastapi-mail

Those packages are usually installed outside this project. Use backend/.venv only for this app
so pins (anyio, httpx, fastapi) do not clash with unrelated tools.

Issue: Notification routes return 503 β€œMongoDB not configured”

Set MONGODB_URL in backend/.env (or config/.env). Start mongod locally or use Atlas.
Restart the API after changing env.

Issue: WhatsApp test messages fail from Twilio

Join the Twilio WhatsApp sandbox from your phone first; use GET /api/notifications/whatsapp/sandbox-info.
For production, use an approved WhatsApp sender and review Twilio/template requirements.

πŸš€ YOU'RE READY!

Clone aqinepal2026 (or extract the ZIP) β†’ Open early-warning-system/ in Cursor β†’ install deps β†’ Run uvicorn β†’ Open the URLs in the table above.

  1. Clone or extract
  2. Open in Cursor
  3. pip install -r backend/requirements.txt (from a venv in backend/)
  4. python -m uvicorn main:app --reload --host 127.0.0.1 --port 8000 from backend/
  5. Open http://127.0.0.1:8000/ or the dashboard/guides links

From there, you can:
- Deploy via Render (see early-warning-system/render.yaml) or another uvicorn host β€” point it at github.com/mamta2009/aqinepal2026**
- Modify with Cursor's AI
- Add real data when ready
- Show UNICEF a working system


πŸ“ FILE LOCATIONS

πŸ“₯ Source: git clone https://github.com/mamta2009/aqinepal2026.git (or early-warning-system.zip)
πŸ“‚ App root: aqinepal2026/early-warning-system/ (or unzip folder)
🎯 Open: Cursor β†’ that folder (contains backend/, landing/, frontend/)
▢️ Run: cd backend && source .venv/bin/activate && python -m uvicorn main:app --reload --host 127.0.0.1 --port 8000
🌐 Landing:    http://127.0.0.1:8000/
πŸ“– Docs hub:    http://127.0.0.1:8000/guides
πŸ“ Register:   http://127.0.0.1:8000/registration
πŸ“Š Dashboard:  http://127.0.0.1:8000/frontend/index.html
πŸ”§ Admin:      http://127.0.0.1:8000/admin/dashboard
πŸ“€ Deploy:      Render (see early-warning-system/render.yaml) or any uvicorn-capable host

⏱️ TIMELINE


FINAL CHECKLIST

You're all set. πŸš€