# Project export: SquadPulse: A Military Healthcare Analytics Platform

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: SquadPulse is a mission-critical platform that unifies real-time heart metrics and advanced analytics, empowering command centers to detect irregularities and keep soldiers at peak readiness.
- Devpost: https://devpost.com/software/squadpulse-a-military-healthcare-analytics-platform
- GitHub: https://github.com/michelleweon/treehacks-2025
- Video: https://www.youtube.com/embed/-LxdBLGoBw4?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 2 GitHub contributor(s) — mweon (9 commits), michelleweon (1 commits)

## Devpost submission (written by the team)

### Inspiration

As our team originally dove into the reality of frontline operations, we discovered that the statistics are sobering: 25+% of military casualties occur during non-combat situations, with cardiovascular events being a significant contributor. Yet somehow, in 2025, we still lack a unified, real-time health monitoring system for our armed forces. Over 60% of military healthcare data remains siloed, never integrated into a unified command center platform. This insight actually hit particularly close to home, as one of our closest roommates back in Cambridge has a family member in the military who suffered a sudden cardiac arrest in the field, nearly losing his life before receiving proper attention. We realized a seamless, real-time data pipeline could have flagged his deteriorating vitals and alerted medics much earlier. That personal scare lit a fire in us to build a solution ensuring no one else’s loved one slips through the cracks. And as a result, we truly believe SquadPulse stands ready to safeguard every heartbeat in our armed forces. Because every soldier’s life is a mission worth protecting.

### What it does

SquadPulse leverages advanced data analytics to classify each soldier’s cardiac signals into categories—regular, irregular, or AFib—based on photoplethysmography (PPG) data and broader metadata. We utilized deep learning models (trained in Python, PyTorch, TensorFlow, and Excel pivot-based data orchestration) to ensure the system and model pinpoints anomalies. Commanders can view squad-level health or deep-dive into individual soldier stats in real time. SquadPulse at its core is a centralized dashboard that provides real-time insights. But where it truly shines is its multimodal analysis engine. We've integrated our PPG analysis with external datasets including EEG signals, stress biomarkers, and performance metrics to provide unprecedented insights into: Combat readiness scoring based on cardiovascular stability Cognitive alertness predictions derived from blood flow patterns Stress-induced decision-making impairment risks Physical exertion limits based on real-time cardiovascular data We’ve integrated a multimodal chatbot that can ingest external datasets to deliver on-the-spot insights. Through natural language queries, leaders can ask questions like, “How is stress level trending across Platoon Bravo?” and instantly see correlated data—like how sleep deprivation might impact decision-making speed, or whether certain squads are close to critical limits in blood oxygen levels or vital cardiac health-adjacent resources. Such an approach, we genuinely believe, can help shape strategic decisions to maintain a healthier and fully aware fighting force.

### How we built it

Our development process focused on three key areas: First is the Data Processing Pipeline, where ... We layered a bunch of pivot tables and specialized macros We also implemented custom PPG signal processing using PyTorch We then built temporal feature extraction networks for waveform analysis We finally developed Excel-based correlation matrices for multimodal data fusion Second is the Machine Learning Architecture, where ... We trained OpenAI’s 3.5 Turbo model on the annotated PPG signals to attempt to predict if a soldier’s breathing is regular, irregular, or a sign of atrial fibrillation. We also used Perplexity’s Sonar Model to generate specialized insights based on each soldier’s individual conditions. Multiple hidden layers and an ensemble of CNN + LSTM architectures handle the time-series nature of the data, and dozens of Excel pivot operations basically serve as an initial feature extraction pipeline—particularly for frequency domain transforms. We then created a hierarchical classification system using ensemble methods and implemented attention mechanisms for temporal pattern recognition And finally, we can't forget about the Interface Development, where ... We built a React/TypeScript frontend for improved IDE support and ease of collaboration. We also implemented the FastAPI backend for rapid data processing We’ve created advanced Excel dashboards using RStudio for detailed statistical analysis Our team is proud to have made a robust pivot-based ETL pipeline in Excel that aggregates thousands of rows from multiple subsystems. This “Excel Core” was shockingly efficient as it let us quickly transform data into training-ready format without specialized data lake solutions. Additionally, the ML-driven insights we’ve been able to derive has been fascinating; we successfully combined deep CNNs, attention-based LSTMs, and standard anomaly detection techniques to create a triple-ensemble classifier with high accuracy on real-world data. And plus, we’ve done all of this while maintaining a scalable architecture. Our microservices (React + FastAPI + TerraAPI) process data quite effortlessly from multiple squads (simultaneously) without bottlenecks. Finally, we love our UI and think it is very intuitive to utilize! Integrating biometric data from multiple device APIs in a single pipeline was tricky. We overcame it with an Excel-driven aggregator; we used pivot tables to scour logs from each device format and then consolidated them into a uniform schema. In terms of balancing latency and accuracy, our early approach used super-deep architectures that slowed real-time classification, and so we ended up implementing real-time partial classification in PyTorch, deferring final, more complex analysis to a background job while pushing quick triaging data to the UI. We wanted a chatbot that not only answered general questions but also correlated multiple signals (ECG + EEG + sleep). And so merging these dramatically different data types forced us to craft a custom bridging module that leveraged Excel’s crosstab lookups to feed the language model. Excel is a hidden powerhouse.. despite numerous data stack options, we rediscovered how powerful and flexible Excel can be, particularly for rapid ETL, pivot-based transformations, and quick “what-if” scenario building before a big integration. Scalable infrastructure is a necessity when working with time-series data. Running up to 1,000 real-time data streams taught us the necessity of using a microservices approach; otherwise, it would be extremely difficult to expand and adapt to changing battlefield conditions. Our work can have genuine impact! Our personal stories and field data confirmed that advanced analytics can be lifesaving. A few seconds of advanced warning for a soldier going into cardiac arrest can literally be the difference between life and death.

## README (from the GitHub repository)

# SquadPulse
**Stanford TreeHacks 2025**

Real-time biometric health risk monitoring for military units.

## What it does
Ingests live PPG, EEG, and physiological stress signals, runs them through 
ensemble deep-learning classifiers, and surfaces squad-level health risk 
scores on a live dashboard — giving commanders situational awareness of 
unit readiness in real time.

## Stack
- **Frontend:** Next.js + React + Tailwind (TypeScript)
- **Backend:** Node.js server + FastAPI (Python)
- **Database:** Supabase (PostgreSQL)
- **ML:** Ensemble classifiers on biometric time-series signals; 
  fine-tuned OpenAI model on custom training data
- **Infra:** Docker, middleware auth, real-time ETL pipeline

## Architecture
Multi-service architecture with separate frontend, backend, server, 
and ML pipeline layers — connected via REST APIs and a Supabase 
Postgres database.


## Detected evidence (automated analysis)

Indexed codebase: 223 recognized source files, 20652 KB.
- CSS (language) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- SQL (language) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- FastAPI (technology) — claimed on Devpost, not found in the code
- PyTorch (technology) — claimed on Devpost, not found in the code
- TensorFlow (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (120 of 3463)

```
__MACOSX/._s25-eng-r2-deliverable
__MACOSX/s25-eng-r2-deliverable/._.editorconfig
__MACOSX/s25-eng-r2-deliverable/._.env
__MACOSX/s25-eng-r2-deliverable/._.env.example
__MACOSX/s25-eng-r2-deliverable/._.eslintignore
__MACOSX/s25-eng-r2-deliverable/._.eslintrc.cjs
__MACOSX/s25-eng-r2-deliverable/._.git
__MACOSX/s25-eng-r2-deliverable/._.gitignore
__MACOSX/s25-eng-r2-deliverable/._.next
__MACOSX/s25-eng-r2-deliverable/._.prettierignore
__MACOSX/s25-eng-r2-deliverable/._.prettierrc.cjs
__MACOSX/s25-eng-r2-deliverable/._.vscode
__MACOSX/s25-eng-r2-deliverable/._app
__MACOSX/s25-eng-r2-deliverable/._components
__MACOSX/s25-eng-r2-deliverable/._components.json
__MACOSX/s25-eng-r2-deliverable/._db.js
__MACOSX/s25-eng-r2-deliverable/._env.mjs
__MACOSX/s25-eng-r2-deliverable/._lib
__MACOSX/s25-eng-r2-deliverable/._middleware.ts
__MACOSX/s25-eng-r2-deliverable/._next-env.d.ts
__MACOSX/s25-eng-r2-deliverable/._next.config.js
__MACOSX/s25-eng-r2-deliverable/._node_modules
__MACOSX/s25-eng-r2-deliverable/._package.json
__MACOSX/s25-eng-r2-deliverable/._postcss.config.cjs
__MACOSX/s25-eng-r2-deliverable/._public
__MACOSX/s25-eng-r2-deliverable/._README.md
__MACOSX/s25-eng-r2-deliverable/._seed.sql
__MACOSX/s25-eng-r2-deliverable/._setup.sql
__MACOSX/s25-eng-r2-deliverable/._tailwind.config.ts
__MACOSX/s25-eng-r2-deliverable/._tsconfig.json
__MACOSX/s25-eng-r2-deliverable/._tsconfig.tsbuildinfo
__MACOSX/s25-eng-r2-deliverable/.vscode/._extensions.json
__MACOSX/s25-eng-r2-deliverable/.vscode/._settings.json
__MACOSX/s25-eng-r2-deliverable/app/_components-navbar/._auth-status.tsx
__MACOSX/s25-eng-r2-deliverable/app/_components-navbar/._mode-toggle.tsx
__MACOSX/s25-eng-r2-deliverable/app/_components-navbar/._navbar.tsx
__MACOSX/s25-eng-r2-deliverable/app/_components-navbar/._user-nav.tsx
__MACOSX/s25-eng-r2-deliverable/app/.__components-navbar
__MACOSX/s25-eng-r2-deliverable/app/._auth
__MACOSX/s25-eng-r2-deliverable/app/._globals.css
__MACOSX/s25-eng-r2-deliverable/app/._layout.tsx
__MACOSX/s25-eng-r2-deliverable/app/._loading.tsx
__MACOSX/s25-eng-r2-deliverable/app/._login
__MACOSX/s25-eng-r2-deliverable/app/._not-found.tsx
__MACOSX/s25-eng-r2-deliverable/app/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/._providers.tsx
__MACOSX/s25-eng-r2-deliverable/app/._settings
__MACOSX/s25-eng-r2-deliverable/app/._species
__MACOSX/s25-eng-r2-deliverable/app/._users
__MACOSX/s25-eng-r2-deliverable/app/auth/._callback
__MACOSX/s25-eng-r2-deliverable/app/auth/callback/._route.ts
__MACOSX/s25-eng-r2-deliverable/app/login/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/login/._user-auth-form.tsx
__MACOSX/s25-eng-r2-deliverable/app/settings/._general
__MACOSX/s25-eng-r2-deliverable/app/settings/._layout.tsx
__MACOSX/s25-eng-r2-deliverable/app/settings/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/settings/._profile
__MACOSX/s25-eng-r2-deliverable/app/settings/general/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/settings/profile/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/settings/profile/._profile-form.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._add-species-dialog.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._delete-species-dialog.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._edit-species-dialog.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._species-card.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._species-details-dialog.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._species-form.tsx
__MACOSX/s25-eng-r2-deliverable/app/species/._species-schema.ts
__MACOSX/s25-eng-r2-deliverable/app/users/._page.tsx
__MACOSX/s25-eng-r2-deliverable/app/users/._user-card.tsx
__MACOSX/s25-eng-r2-deliverable/app/users/._user-details-dialog.tsx
__MACOSX/s25-eng-r2-deliverable/components/._global
__MACOSX/s25-eng-r2-deliverable/components/._icons.tsx
__MACOSX/s25-eng-r2-deliverable/components/._ui
__MACOSX/s25-eng-r2-deliverable/components/global/._sidebar-nav.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._avatar.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._button.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._dialog.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._dropdown-menu.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._form.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._input.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._label.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._select.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._separator.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._textarea.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._toast.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._toaster.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._typography.tsx
__MACOSX/s25-eng-r2-deliverable/components/ui/._use-toast.ts
__MACOSX/s25-eng-r2-deliverable/lib/._client-utils.ts
__MACOSX/s25-eng-r2-deliverable/lib/._reset.d.ts
__MACOSX/s25-eng-r2-deliverable/lib/._schema.ts
__MACOSX/s25-eng-r2-deliverable/lib/._server-utils.ts
__MACOSX/s25-eng-r2-deliverable/lib/._utils.ts
.editorconfig
.env.example
.eslintignore
.eslintrc.cjs
.gitignore
.prettierignore
.prettierrc.cjs
.vscode/extensions.json
.vscode/settings.json
app-build-manifest.json
app/_components-navbar/auth-status.tsx
app/_components-navbar/mode-toggle.tsx
app/_components-navbar/navbar.tsx
app/_components-navbar/user-nav.tsx
app/api/analyze/route.ts
app/api/classify-recording/route.ts
app/api/process-recordings/route.ts
app/api/upload-recordings/route.ts
app/auth/callback/route.ts
app/components/auth-button.tsx
app/components/auth-check.tsx
app/data/ppg_exports_20241126_094919/afib/afib_1.csv
app/data/ppg_exports_20241126_094919/afib/afib_1.json
app/data/ppg_exports_20241126_094919/afib/afib_10.csv
app/data/ppg_exports_20241126_094919/afib/afib_100.csv
app/data/ppg_exports_20241126_094919/afib/afib_1000.csv
[3343 more files omitted for size]
```

### Dependencies

- package.json: @hookform/resolvers@^3.3.2, @radix-ui/react-avatar@^1.0.4, @radix-ui/react-dialog@^1.0.5, @radix-ui/react-dropdown-menu@^2.0.6, @radix-ui/react-label@^2.0.2, @radix-ui/react-select@^2.0.0, @radix-ui/react-separator@^1.0.3, @radix-ui/react-slot@^1.0.2, @radix-ui/react-toast@^1.1.5, @supabase/auth-helpers-nextjs@^0.10.0, @supabase/ssr@^0.5.2, @supabase/supabase-js@^2.39.1, @t3-oss/env-nextjs@^0.7.1, @total-typescript/ts-reset@^0.5.1, @types/eslint@^8.56.0, @types/node@^20.10.5, @types/react@^18.3.18, @types/react-dom@^18.3.5, @typescript-eslint/eslint-plugin@^6.15.0, @typescript-eslint/parser@^6.15.0, autoprefixer@^10.4.16, class-variance-authority@^0.7.0, client-only@^0.0.1, clsx@^2.0.0, cross-env@^7.0.3, csv-parse@^5.6.0, dotenv-cli@^7.3.0, encoding@^0.1.13, eslint@^8.56.0, eslint-config-next@^14.0.4, eslint-config-prettier@^9.1.0, framer-motion@^12.4.3, jszip@^3.10.1, lucide-react@^0.299.0, next@^14.2.23, next-themes@^0.2.1, openai@^4.85.1, postcss@^8.4.32, postgres@^3.4.5, prettier@^3.1.1, prettier-plugin-organize-imports@^3.2.4, prettier-plugin-tailwindcss@^0.5.9, react@^18.3.1, react-dom@^18.3.1, react-hook-form@^7.49.2, react-select@^5.8.0, recharts@^2.15.1, server-only@^0.0.1, supabase@^1.123.4, tailwind-merge@^2.2.0, tailwindcss@^3.4.0, tailwindcss-animate@^1.0.7, typescript@^5.7.3, zod@^3.22.4

### Recent commits (newest first)

- Rename project to SquadPulse and enhance README
- finished
- debugged
- jeff
- update
- trying openai api on jeffreys
- performed data analysis
- created ai model
- added more files
- upload zip file successful
- added dark mode to dashboard
- created working dashboard
- rick yang
- added webpage
- i did some front-end
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### __MACOSX/s25-eng-r2-deliverable/._README.md

```markdown
    Mac OS X            	   2   q      �                                      ATTR       �   �                     �     com.apple.provenance   Nb���)�B
```

### package.json

```
{
  "//": [
    "This is an area for comments",
    "As of Jul 11, when using Prettier v3 and prettier-plugin-tailwindcss together, third party plugin compatibility has been disabled temporarily. This means Svelte, Astro, etc. are not supported. This may not be an issue with more recent updates. Read more here: https://github.com/tailwindlabs/prettier-plugin-tailwindcss/issues/176"
  ],
  "name": "starter-project-2023-v2",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "cross-env SKIP_ENV_VALIDATION=true next lint",
    "lint:fix": "npm run lint -- --fix",
    "prettier": "npx prettier . --check",
    "prettier:fix": "npm run prettier -- --write",
    "format": "npm run prettier:fix && npm run lint:fix",
    "_types": "cross-env-shell \"supabase gen types typescript --db-url $SECRET_SUPABASE_CONNECTION_STRING > ./lib/schema.ts && prettier lib/schema.ts --write\"",
    "types": "dotenv -- npm run _types"
  },
  "dependencies": {
    "@hookform/resolvers": "^3.3.2",
    "@radix-ui/react-avatar": "^1.0.4",
    "@radix-ui/react-dialog": "^1.0.5",
    "@radix-ui/react-dropdown-menu": "^2.0.6",
    "@radix-ui/react-label": "^2.0.2",
    "@radix-ui/react-select": "^2.0.0",
    "@radix-ui/react-separator": "^1.0.3",
    "@radix-ui/react-slot": "^1.0.2",
    "@radix-ui/react-toast": "^1.1.5",
    "@supabase/auth-helpers-nextjs": "^0.10.0",
    "@supabase/ssr": "^0.5.2",
    "@supabase/supabase-js": "^2.39.1",
    "@t3-oss/env-nextjs": "^0.7.1",
    "class-variance-authority": "^0.7.0",
    "client-only": "^0.0.1",
    "clsx": "^2.0.0",
    "csv-parse": "^5.6.0",
    "encoding": "^0.1.13",
    "framer-motion": "^12.4.3",
    "jszip": "^3.10.1",
    "lucide-react": "^0.299.0",
    "next": "^14.2.23",
    "next-themes": "^0.2.1",
    "openai": "^4.85.1",
    "postgres": "^3.4.5",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-hook-form": "^7.49.2",
    "react-select": "^5.8.0",
    "recharts": "^2.15.1",
    "server-only": "^0.0.1",
    "tailwind-merge": "^2.2.0",
    "tailwindcss-animate": "^1.0.7",
    "zod": "^3.22.4"
  },
  "devDependencies": {
    "@total-typescript/ts-reset": "^0.5.1",
    "@types/eslint": "^8.56.0",
    "@types/node": "^20.10.5",
    "@types/react": "^18.3.18",
    "@types/react-dom": "^18.3.5",
    "@typescript-eslint/eslint-plugin": "^6.15.0",
    "@typescript-eslint/parser": "^6.15.0",
    "autoprefixer": "^10.4.16",
    "cross-env": "^7.0.3",
    "dotenv-cli": "^7.3.0",
    "eslint": "^8.56.0",
    "eslint-config-next": "^14.0.4",
    "eslint-config-prettier": "^9.1.0",
    "postcss": "^8.4.32",
    "prettier": "^3.1.1",
    "prettier-plugin-organize-imports": "^3.2.4",
    "prettier-plugin-tailwindcss": "^0.5.9",
    "supabase": "^1.123.4",
    "tailwindcss": "^3.4.0",
    "typescript": "^5.7.3"
  }
}

```

### types/package.json

```
{"type": "module"}
```

### app/layout.tsx

```typescript
import { ModeToggle } from "@/app/_components-navbar/mode-toggle";
import { Toaster } from "@/components/ui/toaster";
import AuthStatus from "./_components-navbar/auth-status";
import Navbar from "./_components-navbar/navbar";
import "./globals.css";
import { Providers } from "./providers";

export const metadata = {
  title: "SquadPulse",
  description: "Tree Hacks 2025 -- Developed by: Jeffrey Zhou, Rick Yang, Michelle Weon",
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      {/* Hydration warning suppressed because of next-themes https://github.com/pacocoursey/next-themes */}
      <body>
        <Providers>
          <div className="flex-col md:flex">
            <div className="border-b">
              <div className="flex h-16 items-center px-4">
                <Navbar className="mx-6" />
                <div className="ml-auto flex items-center space-x-4">
                  <ModeToggle />
                  <AuthStatus />
                </div>
              </div>
            </div>
            {/* Conditionally display website if logged in, else display login page */}
            <div className="space-y-6 p-10 pb-16 md:block">
              <main>{children}</main>
            </div>
          </div>
        </Providers>
        <Toaster />
      </body>
    </html>
  );
}

```

### supabase/index.ts

```typescript
// supabase/functions/import-csv/index.ts
import { serve } from 'https://esm.sh/@std/http/server';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { Client } from 'https://deno.land/x/postgres@v0.17.0/mod.ts';
import { parse } from 'https://esm.sh/csv-parse@5.5.3';

const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '';
const SUPABASE_ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY') ?? '';

const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

const dbConfig = {
    connectionString: Deno.env.get('SUPABASE_DB_URL') ?? '', // Ensure you set this environment variable
};


serve(async (req) => {
  try {
      const { bucket, name } = await req.json();

      const { data, error } = await supabase.storage
          .from(bucket)
          .download(name)

      if (error) {
          console.error("Error downloading file from storage: ", error);
          throw new Error("Unable to download file from storage")
      }

      const csvText = new TextDecoder().decode(data); //Decode the CSV
      const results = Array.from(parse(csvText, {
          header: true,
          skipEmptyLines: true
        })
      );

      //Get database name from filename
      const tableName = name.includes('metadata') ? 'metadata' : 'recordings';

      //Initialize a Supabase database client
      const db = new Client(dbConfig);
      await db.connect();

      //Batch Insert using a dynamic query
      const batchSize = 100;

      for (let i = 0; i < results.length; i += batchSize) {
        const batch = results.slice(i, i + batchSize);

        if (batch.length > 0) {
          const columns = Object.keys(batch[0] as Object);
          const values = batch.map(obj => `(${columns.map(col => {
            let val = (obj as any)[col];
            if (val === null || val === undefined) return 'NULL';
            if (typeof val === 'string') val = val.replace(/'/g, "''"); // Escape single quotes in string values
            return typeof val === 'string' ? `'${val}'` : val;
          }).join(',')})`).join(',');

          const insertCommand = `
            INSERT INTO ${tableName} (${columns.join(',')})
            VALUES ${values};
          `;
          console.log(`Executing batch insert for rows ${i} to ${i + batch.length - 1}`);
          try {
            await db.queryObject(insertCommand);
          } catch (insertError) {
            console.error(`Error inserting batch of rows ${i} to ${i + batchSize - 1}:`, insertError);
            throw insertError; // Re-throw the error to stop processing or handle differently
          }
        }
      }
        return new Response(
            JSON.stringify({ message: "Data insertion successful" }),
            {
                status: 200,
                headers: { "Content-Type": "application/json" },
            }
        );

    } catch (error) {
        console.error("Error in Edge Function: ", error);
        return new Response(JSON.stringify({ error: error.message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
        });
    }
});

```

### app/page.tsx

```typescript
"use client";

import { Separator } from "@/components/ui/separator";
import { TypographyH2, TypographyP } from "@/components/ui/typography";
import { motion } from "framer-motion";
import Image from "next/image";

const fadeIn = {
  initial: { opacity: 0, y: 20 },
  animate: { opacity: 1, y: 0 },
  transition: { duration: 0.5 },
};

const staggerChildren = {
  animate: {
    transition: {
      staggerChildren: 0.2,
    },
  },
};

export default function Home() {
  return (
    <motion.div initial="initial" animate="animate" variants={staggerChildren}>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.7 }}
        className="mb-8 flex justify-center"
      >
        <Image src="/logo.png" alt="SquadPulse Logo" width={100} height={100} priority />
      </motion.div>

      <motion.div variants={fadeIn}>
        <TypographyH2>
          <motion.span
            className="text-green-400"
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.7, delay: 0.2 }}
          >
            SquadPulse
          </motion.span>
          : Command-Level Health Intelligence for Mission Readiness
        </TypographyH2>
      </motion.div>

      <motion.div variants={fadeIn}>
        <TypographyP>
          SquadPulse transforms individual health data into actionable squad-level insights, enabling commanders to make
          informed decisions about mission readiness and tactical deployment.
        </TypographyP>
      </motion.div>

      <Separator className="my-4" />

      <motion.div variants={fadeIn}>
        <TypographyP className="font-semibold text-muted-foreground">Key Capabilities:</TypographyP>
      </motion.div>

      <motion.ul className="mt-2 list-disc space-y-2 pl-6">
        {[
          "Real-time heart health monitoring using advanced PPG waveform analysis",
          "Squad-wide health trend identification and early warning system",
          "Predictive analytics for cardiovascular anomalies and combat readiness",
          "Tactical deployment recommendations based on health metrics",
        ].map((capability, index) => (
          <motion.li
            key={index}
            className="text-muted-foreground"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5, delay: 0.5 + index * 0.2 }}
          >
            {capability}
          </motion.li>
        ))}
      </motion.ul>

      <Separator className="my-4" />

      <motion.div variants={fadeIn} transition={{ delay: 1.5 }}>
        <TypographyP>
          Leveraging over 2,800 PPG recordings and advanced AI analysis, SquadPulse provides commanders with a
          comprehensive view of their squad&apos;s cardiovascular health, stress levels, and overall readiness status.
        </TypographyP>
      </motion.div>

      <motion.div variants={fadeIn} transition={{ delay: 1.7 }}>
        <TypographyP className="mt-4">
          <motion.span className="font-semibold" whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
            Secure Access:
          </motion.span>{" "}
          Log in through the top right to access your squad&apos;s health command center.
        </TypographyP>
      </motion.div>
    </motion.div>
  );
}

```

### app/settings/page.tsx

```typescript
import { redirect } from "next/navigation";

export default function Settings() {
  redirect("/settings/general");
}

```

### backend/app/main.py

```python
from fastapi import FastAPI
from app.routes import squads, alerts, ai

app = FastAPI(title="Health Insights API", description="API for squad insights, alerts, and AI-driven health predictions.")

# Include API routes
app.include_router(squads.router, prefix="/squads", tags=["Squads"])
app.include_router(alerts.router, prefix="/alerts", tags=["Alerts"])
app.include_router(ai.router, prefix="/ai", tags=["AI Predictions"])

@app.get("/")
def read_root():
    return {"message": "Welcome to the Health Insights API"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

```

### app/login/page.tsx

```typescript
import { createServerSupabaseClient } from "@/lib/server-utils";
import { redirect } from "next/navigation";
import UserAuthForm from "./user-auth-form";

export default async function LoginPage() {
  // Create supabase server component client and obtain user session from stored cookie
  const supabase = createServerSupabaseClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (session) {
    // Users who are already signed in should be redirected to species page
    redirect("/species");
  }

  return (
    <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
      <div className="flex flex-col space-y-2 text-center">
        <h1 className="text-2xl font-semibold tracking-tight">Sign Up / Log In</h1>
        <p className="text-sm text-muted-foreground">Enter your email below to sign in or create a new account.</p>
      </div>
      <UserAuthForm />
    </div>
  );
}

```

### app/users/page.tsx

```typescript
import { Separator } from "@/components/ui/separator";
import { TypographyH2 } from "@/components/ui/typography";
import { createServerSupabaseClient } from "@/lib/server-utils";
import { redirect } from "next/navigation";
import UserCard from "./user-card";

export default async function UsersList() {
  // Create supabase server component client and obtain user session from stored cookie
  const supabase = createServerSupabaseClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    // this is a protected route - only users who are signed in can view this route
    redirect("/");
  }

  const { data: users } = await supabase
    .from("profiles")
    .select("*")
    .order("id", { ascending: false });

  return (
    <>
      <div className="mb-5 flex flex-wrap items-center justify-between gap-4">
        <TypographyH2>Users List</TypographyH2>
      </div>
      <Separator className="my-4" />
      <div className="flex flex-wrap justify-center">
        {users?.map((users) => <UserCard key={users.id} user={users} />)}
      </div>
    </>
  );
}

```

[170 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]