# Project export: FinPilot AI

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: OpenAI Build Week
- Tagline: An AI-powered financial operating system that unifies expenses, investments, and personalized financial intelligence in one platform.
- Devpost: https://devpost.com/software/finpilot-2zwqi6
- GitHub: https://github.com/imposterbharathkumarburugu15-cpu/fintech-ai
- Demo: https://fintech-ai-wine.vercel.app/
- Video: https://www.youtube.com/embed/5KtN04k-e2I?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 6 GitHub contributor(s) — bharath (58 commits), Chinmayee Wuriti (48 commits), Pri (10 commits), SU (4 commits), yashshawini (4 commits), Copilot App (2 commits)

## Devpost submission (written by the team)

### Inspiration

Managing personal finances typically involves switching between multiple applications, one for banking, another for investments, a third for market news, and yet another for financial questions. Each tool solves a specific problem, but none provides a complete view of a user's financial life. We wanted to build a single platform that combines expenses, investments, market insights, and financial guidance in one place. Instead of just displaying transactions and charts, FinPilot helps users understand their finances through meaningful insights and contextual information. What It Does FinPilot combines everyday financial management with investment tracking and intelligent analysis into a single platform. Expense Management Automatically imports bank transaction SMS messages on Android Detects income and expenses Categorizes transactions Tracks spending over time Generates summaries and spending insights Identifies recurring payments and unusual spending patterns Investment Tracking Monitor stock portfolios Create and manage watchlists Research companies and market trends View portfolio performance and allocation Track sector diversification Financial Assistant FinPilot includes an integrated financial assistant that helps users understand their spending patterns, analyze portfolio performance, learn investment concepts, answer questions using their own financial data, and explore budgeting strategies. Instead of providing generic responses, it uses the user's financial information to deliver relevant and personalized guidance. Personalized Notifications Rather than showing every market headline, FinPilot highlights news and updates relevant to the user's portfolio and watchlists. Intelligent Report Generation FinPilot automatically generates comprehensive financial reports that analyze user data and present actionable insights. The system processes transaction history, portfolio data, and spending patterns to create professional reports with charts and visualizations. Users can export these reports as PDF files for sharing with financial advisors or for personal record keeping. Goal Tracking Users can set financial goals such as saving for a car, building an emergency fund, or growing an investment portfolio. FinPilot tracks progress against these goals, estimates completion timelines based on current savings rates, and provides recommendations to accelerate progress. Smart Alerts FinPilot monitors financial activity and generates alerts for situations that may require attention, including budget exceedances, unusual spending patterns, portfolio concentration risks, and important market events relevant to user holdings. Why We Used Codex and GPT We incorporated OpenAI's Codex and GPT models at different stages of development to accelerate building while enabling intelligent user-facing features. Codex for Development Acceleration Codex acted as an engineering partner throughout the development lifecycle. It helped us design the overall system architecture, plan a scalable project structure, and define API flows. In the frontend, Codex accelerated development of React components, responsive layouts, dashboards, and interactive forms. For the backend, it assisted in creating FastAPI endpoints, handling file uploads, organizing API routes, and structuring the application into modular components. When we encountered issues, Codex helped identify root causes and suggest improvements. It also helped refactor repetitive code into reusable components, making the application easier to maintain. By reducing time spent on repetitive development tasks, Codex allowed us to focus on building better features and improving the overall user experience. GPT for Intelligence GPT powers the core intelligence features of FinPilot. When users upload transaction history, GPT analyzes spending patterns, categorizes expenses, identifies recurring payments, and generates personalized financial insights. For stock research, GPT explains companies in simple language by generating business summaries and highlighting strengths and risks. The Financial Assistant allows users to ask questions about their finances and receive context-aware responses based on their financial information instead of generic answers. GPT also generates personalized financial reports that summarize spending behavior, highlight important insights, and recommend practical actions users can take to improve their financial well-being. Together, Codex helped us build FinPilot efficiently, and GPT made it intelligent by transforming financial data into meaningful insights and natural conversations. How We Built It Frontend React with Vite for the web application React Native CLI for the Android mobile application Backend Express.js for the API server TypeScript for type safety OpenAI APIs for intelligent features Alpha Vantage APIs for market data Database Supabase as the backend-as-a-service platform PostgreSQL for data storage Row-Level Security (RLS) for data protection Authentication via Supabase Auth Cloud Storage for file handling Both web and Android applications share the same backend and database, allowing data captured on one device to instantly appear across the platform. The database was designed as the single source of truth, with separate models for transactions, investments, watchlists, alerts, reports, and goals. Technical Highlights Automatic SMS Transaction Parsing Instead of relying on sender IDs, which vary significantly between banks, we analyze the content of each SMS to identify financial transactions. The parser can detect debit and credit transactions, extract amounts, identify merchants, ignore OTP and promotional messages, distinguish balances from transaction amounts, and prevent duplicate uploads. This approach supports multiple banks without maintaining bank-specific rules. Secure Multi-User Architecture Financial data is protected using PostgreSQL Row-Level Security (RLS), ensuring users can only access their own records. Authentication and authorization are integrated throughout the application to provide secure access across web and mobile platforms. Efficient Request Processing Most requests are handled through database queries and application logic before invoking language models. This keeps responses fast, reduces unnecessary API usage, and lowers operational costs while reserving advanced processing for tasks that genuinely benefit from it. Data Visualization FinPilot uses interactive charts and visualizations to help users understand their financial data. Spending distributions, monthly trends, and portfolio allocations are displayed through responsive charts that make complex data easier to interpret. Challenges We Ran Into Building FinPilot required solving problems across mobile development, backend architecture, databases, and financial data processing. Key challenges included: Supporting multiple bank SMS formats Preventing duplicate transaction imports Designing a scalable financial database Implementing secure multi-user access with Row-Level Security Synchronizing data between mobile and web applications Balancing advanced language features with performance and cost Managing collaboration and Git workflows with multiple contributors

## README (from the GitHub repository)

# FinPilot AI

## Inspiration

Managing personal finances today is surprisingly fragmented. People use one app to check bank transactions, another to track investments, another to read financial news, and often a chatbot to ask financial questions. None of these services truly understand the user's complete financial picture.

We wanted to build something different.

Our vision was to create **FinPilot AI**, an AI-powered financial operating system that unifies expenses, investments, market intelligence, and personalized financial guidance into a single platform. Instead of simply displaying numbers and charts, FinPilot AI explains what happened, why it happened, and what actions the user should consider.

---

## What it does

FinPilot AI combines multiple financial tools into one intelligent platform.

### Expense Intelligence

- Automatically imports bank transactions from SMS (Android)
- Categorizes spending
- Tracks income and expenses
- Generates spending insights and summaries

### Investment Intelligence

- Portfolio tracking
- Stock research
- Personalized market analysis
- Watchlists and investment monitoring

### Nexus AI

Nexus AI is a finance-focused AI assistant that helps users understand:

- Their own financial data
- Investment concepts
- Spending habits
- Portfolio performance
- Financial planning

Unlike general-purpose chatbots, Nexus AI is designed specifically for finance.

### Personalized Alerts

Rather than showing generic market news, FinPilot AI checks whether news actually affects the user's own portfolio before generating alerts.

---

## How We Built It

### Frontend

- React
- Vite
- React Native CLI (Android)

### Backend

- Express.js
- TypeScript
- OpenAI GPT-5.6 API
- Finnhub API

### Database

- Supabase
- PostgreSQL
- Row-Level Security (RLS)
- Authentication
- Cloud Storage

The web application and Android application share the same backend and database, allowing transactions captured on a phone to instantly appear on the web dashboard.

One of our biggest design principles was keeping the database as the single source of truth. Expenses, transactions, watchlists, AI reports, and alerts are stored independently so every feature can build upon reliable financial data.

---

## Technical Highlights

### Automatic SMS Transaction Parsing

One of the most challenging parts of the project was creating a reliable SMS parser.

Instead of relying on bank sender IDs—which vary across banks—we parse transaction content. This allows the parser to work across multiple Indian banks without maintaining bank-specific rules.

The parser:

- Detects debit and credit transactions
- Extracts transaction amounts
- Identifies merchants when possible
- Ignores OTPs and promotional messages
- Filters account balances from transaction amounts
- Prevents duplicate transaction uploads

### Secure Multi-User Architecture

Security was one of our primary design goals.

Every user's financial data is isolated using PostgreSQL Row-Level Security (RLS), ensuring users can only access their own records.

### AI-First Architecture

Instead of sending every request directly to an LLM, FinPilot AI first performs inexpensive database filtering and rule-based processing. AI is only used where it genuinely adds value, reducing latency, API usage, and operational costs.

---

## APIs and Services Used

### OpenAI GPT-5.6 API

Used to power Nexus AI, generate financial insights, explain investment concepts, answer finance-related questions, and create personalized AI financial reports.

**Reason:** GPT-5.6 enables natural conversations and personalized financial assistance instead of simply displaying raw financial data.

### Finnhub API

Used to retrieve real-time stock prices, company profiles, financial news, and market information.

**Reason:** Reliable live market data is essential for investment research, portfolio monitoring, and personalized market analysis.

### Supabase

Used for authentication, PostgreSQL database management, Row-Level Security (RLS), and cloud storage.

**Reason:** Supabase provides a secure, scalable backend while ensuring each user's financial information remains isolated and protected.

### Vercel

Used to deploy the React web application.

**Reason:** Fast frontend deployment with automatic CI/CD and global hosting.

### Render

Used to deploy the Express backend.

**Reason:** Reliable backend hosting with environment variable management and easy deployment.

---

## How We Collaborated with Codex

OpenAI Codex was an engineering assistant throughout the development of FinPilot AI. Rather than using it to build the application automatically, we used it to accelerate development, explore implementation approaches, and solve technical challenges while keeping all product, engineering, and design decisions within our team.

During the planning stage, Codex helped us evaluate different architectural approaches and organize the project into a clean React frontend, Express backend, and Supabase-powered backend. This allowed us to maintain a modular and scalable codebase as new features were added.

During implementation, Codex accelerated repetitive engineering tasks such as creating reusable React components, defining TypeScript interfaces, building Express API routes, integrating Supabase, and connecting external APIs like Finnhub. It also helped explain errors, troubleshoot deployment issues on Vercel and Render, improve code quality, and suggest cleaner implementations during refactoring.

While Codex significantly improved our development speed, every generated solution was reviewed, tested, modified, and integrated by our team. Decisions such as the overall product vision, database design, user experience, SMS transaction parsing logic, AI workflow, and feature prioritization were made by us based on the requirements of the project.

Using Codex allowed us to spend less time on repetitive coding tasks and more time improving the product, refining the user experience, and building meaningful AI-powered features.

---

## How GPT-5.6 Contributed

GPT-5.6 powers Nexus AI, the AI financial copilot integrated into FinPilot AI.

Instead of acting as a general-purpose chatbot, GPT-5.6 interprets financial information and provides personalized assistance based on user data.

GPT-5.6 is responsible for:

- Answering finance-related questions
- Explaining stocks and companies in simple language
- Summarizing spending behaviour
- Generating AI-powered financial reports
- Providing personalized financial insights
- Helping users understand investment opportunities and financial health

Our goal was to make financial information understandable rather than overwhelming. GPT-5.6 enables users to interact with their finances naturally instead of interpreting complex charts and numbers themselves.

---

## Challenges We Ran Into

This project involved solving challenges across mobile development, backend architecture, databases, and AI.

Some of the biggest challenges included:

- Parsing dozens of different bank SMS formats
- Eliminating duplicate transaction uploads
- Designing a scalable financial database
- Building secure multi-user authentication with Row-Level Security
- Synchronizing mobile and web applications through a shared backend
- Integrating AI while keeping response costs practical
- Managing team collaboration and Git workflows during development

Each challenge pushed us to rethink our architecture and build reliable, scalable solutions instead of quick fixes.

---

## What We Learned

This project taught us much more than simply building another web application.

We learned:

- Designing secure multi-user systems
- Mobile-native development with React Native
- PostgreSQL database design
- Authentication and authorization
- AI application architecture
- Prompt engineering
- Financial data modeling
- Real-world API integration
- Building scalable full-stack applications

Perhaps the biggest lesson was that AI alone i

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 38 recognized source files, 401 KB.
- CSS (language) — detected in the code
- Express (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- OpenAI (technology) — detected in the code
- React (technology) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Node.js (technology) — claimed on Devpost, not found in the code
- PostgreSQL (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code
- AI coding agent: GitHub Copilot — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (51 of 51)

```
.env.example
.gitignore
.vscode/settings.json
bun.lock
fix_nexus.cjs
fix_submit.cjs
fix-jsx.cjs
fix-jsx.js
fix.cjs
index.html
metadata.json
package.json
patch_prompt.cjs
patch.cjs
README.md
server.ts
src/App.tsx
src/components/AddExpenseModal.jsx
src/components/AddTransactionModal.jsx
src/components/CashFlowChart.jsx
src/components/Dashboard.jsx
src/components/DataIntelligence.jsx
src/components/ExpenseIntelligence.jsx
src/components/GoalPlanner.jsx
src/components/GoalTracker.tsx
src/components/Login.jsx
src/components/MarketIntelligence.jsx
src/components/NexusAI.jsx
src/components/PortfolioIntelligence.jsx
src/components/ReportCenter.jsx
src/components/reports/RecommendationCard.tsx
src/components/reports/ReportCharts.tsx
src/components/reports/ReportRenderer.tsx
src/components/reports/ReportSkeleton.tsx
src/components/reports/ReportViewer.tsx
src/components/Sidebar.jsx
src/components/SmartAlerts.jsx
src/components/StockResearch.jsx
src/components/TopNav.jsx
src/index.css
src/lib/transactions.js
src/lib/utils.js
src/main.jsx
src/services/pdfExportService.ts
src/services/reportDataService.ts
src/supabaseClient.js
src/types/report.types.ts
src/utils/reportCalculations.ts
supabaseClient.js
tsconfig.json
vite.config.ts
```

### Dependencies

- package.json: @google/genai@^2.12.0, @supabase/supabase-js@^2.110.7, @tailwindcss/vite@^4.1.14, @types/cors@^2.8.19, @types/express@^4.17.21, @types/html2canvas@^0.5.35, @types/jspdf@^1.3.3, @types/node@^22.14.0, @types/puppeteer@^5.4.7, @vitejs/plugin-react@^5.0.4, autoprefixer@^10.4.21, clsx@^2.1.1, cors@^2.8.6, dotenv@^17.2.3, esbuild@^0.25.0, express@^4.21.2, framer-motion@^11.18.2, html2canvas@^1.4.1, html2pdf.js@^0.14.0, jspdf@^4.2.1, lucide-react@^0.546.0, motion@^12.23.24, openai@^6.48.0, papaparse@^5.5.4, puppeteer@^25.3.0, react@^19.0.1, react-dom@^19.0.1, react-markdown@^10.1.0, recharts@^3.10.0, tailwind-merge@^3.6.0, tailwindcss@^4.1.14, tsx@^4.21.0, typescript@~5.8.2, vite@^6.2.3, vite@^6.2.3, yahoo-finance2@^2.13.3

### Recent commits (newest first)

- Update SmartAlerts.jsx
- ui=-changed
- Merge pull request #5 from imposterbharathkumarburugu15-cpu/AI-report-generation-chinmayee
- Done with PDF renderring
- Done with PDF renderring
- PDF Rendering
- PDF Rendering
- Merge branch 'main' of https://github.com/imposterbharathkumarburugu15-cpu/fintech-ai into AI-report-generation-chinmayee
- PDF Rendering
- NAME-CHANGd
- PDF Rendering
- PDF Rendering
- ui=-changed
- PDF Rendering
- PDF Rendering
- PDF Rendering
- PDF Rendering
- feat: Complete Portfolio Report overhaul
- PDF Rendering
- feat: Complete Portfolio Report overhaul

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

### package.json

```
{
  "name": "react-example",
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "tsx server.ts",
    "build": "vite build && esbuild server.ts --bundle --platform=node --format=cjs --packages=external --sourcemap --outfile=dist/server.cjs",
    "start": "node dist/server.cjs",
    "clean": "rm -rf dist server.js",
    "lint": "tsc --noEmit"
  },
  "dependencies": {
    "@google/genai": "^2.12.0",
    "@supabase/supabase-js": "^2.110.7",
    "@tailwindcss/vite": "^4.1.14",
    "@vitejs/plugin-react": "^5.0.4",
    "clsx": "^2.1.1",
    "cors": "^2.8.6",
    "dotenv": "^17.2.3",
    "express": "^4.21.2",
    "framer-motion": "^11.18.2",
    "html2canvas": "^1.4.1",
    "html2pdf.js": "^0.14.0",
    "jspdf": "^4.2.1",
    "lucide-react": "^0.546.0",
    "motion": "^12.23.24",
    "openai": "^6.48.0",
    "papaparse": "^5.5.4",
    "puppeteer": "^25.3.0",
    "react": "^19.0.1",
    "react-dom": "^19.0.1",
    "react-markdown": "^10.1.0",
    "recharts": "^3.10.0",
    "tailwind-merge": "^3.6.0",
    "vite": "^6.2.3",
    "yahoo-finance2": "^2.13.3"
  },
  "devDependencies": {
    "@types/cors": "^2.8.19",
    "@types/express": "^4.17.21",
    "@types/html2canvas": "^0.5.35",
    "@types/jspdf": "^1.3.3",
    "@types/node": "^22.14.0",
    "@types/puppeteer": "^5.4.7",
    "autoprefixer": "^10.4.21",
    "esbuild": "^0.25.0",
    "tailwindcss": "^4.1.14",
    "tsx": "^4.21.0",
    "typescript": "~5.8.2",
    "vite": "^6.2.3"
  }
}
```

### src/main.jsx

```javascript
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

```

### src/App.tsx

```typescript
// src/App.tsx

import { useState, useEffect } from "react";
import { TopNav } from "./components/TopNav";
import { NexusChat } from "./components/NexusAI";
import { AddTransactionModal } from "./components/AddTransactionModal";
import { Dashboard } from "./components/Dashboard";
import { ExpenseIntelligence  } from "./components/ExpenseIntelligence";
import { StockResearch } from "./components/StockResearch";
import { PortfolioIntelligence } from "./components/PortfolioIntelligence";
import { GoalPlanner } from "./components/GoalPlanner";
import { ReportCenter } from "./components/ReportCenter";
import { MarketIntelligence } from "./components/MarketIntelligence";
import { SmartAlerts } from "./components/SmartAlerts";
import { Login } from "./components/Login";
import { supabase } from "./supabaseClient";
import ReportViewer from './components/reports/ReportViewer';

type ViewType = "dashboard" | "expenses" | "stocks" | "portfolio" | "goals" | "reports" | "markets" | "alerts";

function App() {
  const [isChatOpen, setIsChatOpen] = useState(false);
  const [isAddTransactionOpen, setIsAddTransactionOpen] = useState(false);
  const [activeView, setActiveView] = useState<ViewType>("dashboard");
  const [selectedReportType, setSelectedReportType] = useState<string>("monthly");
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    if (!supabase) {
      console.error('❌ Supabase client not initialized');
      setLoading(false);
      return;
    }

    supabase.auth.getSession()
      .then(({ data: { session } }) => {
        setUser(session?.user || null);
        setLoading(false);
      })
      .catch((err) => {
        console.error('❌ Error getting session:', err);
        setLoading(false);
      });

    const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
      setUser(session?.user || null);
      setLoading(false);
    });

    return () => {
      subscription?.unsubscribe();
    };
  }, []);

  const handleViewChange = (view: string) => {
    setActiveView(view as ViewType);
  };

  const handleExport = (format: 'pdf' | 'excel'): void => {
    console.log(`Exporting report as ${format}`);
    alert(`${format.toUpperCase()} export coming soon!`);
  };

  const renderView = () => {
    switch (activeView) {
      case "dashboard":
        return <Dashboard onViewChange={setActiveView} onToggleChat={() => setIsChatOpen(true)} />;
      case "expenses":
        return <ExpenseIntelligence />;
      case "stocks":
        return <StockResearch />;
      case "portfolio":
        return <PortfolioIntelligence />;
      case "goals":
        return <GoalPlanner />;
      case "reports":
        return (
          <div className="p-4 md:p-6">
            <div className="flex flex-wrap gap-2 mb-4">
              <button
                onClick={() => setSelectedReportType("monthly")}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
                  selectedReportType === "monthly"
                    ? "bg-blue-600 text-white"
                    : "bg-gray-800 text-gray-400 hover:bg-gray-700"
                }`}
              >
                Monthly Report
              </button>
              <button
                onClick={() => setSelectedReportType("expense")}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
                  selectedReportType === "expense"
                    ? "bg-blue-600 text-white"
                    : "bg-gray-800 text-gray-400 hover:bg-gray-700"
                }`}
              >
                Expense Analysis
              </button>
              <button
                onClick={() => setSelectedReportType("investment")}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
                  selectedReportType === "investment"
                    ? "bg-blue-600 text-white"
                    : "bg-gray-800 text-gray-400 hover:bg-gray-700"
                }`}
              >
                Portfolio Report
              </button>
              <button
                onClick={() => setSelectedReportType("health")}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition ${
                  selectedReportType === "health"
                    ? "bg-blue-600 text-white"
                    : "bg-gray-800 text-gray-400 hover:bg-gray-700"
                }`}
              >
                Health Score
              </button>
            </div>     
            
            {user?.id ? (
              <ReportViewer 
                userId={user.id}
                reportType={selectedReportType}
                onExport={handleExport}
              />
            ) : (
              <div className="p-8 text-center text-gray-400 bg-gray-800/50 rounded-xl border border-gray-700">
                <p className="text-lg">Please login to view your financial report</p>
                <p className="text-sm mt-2">Sign in to see personalized financial insights</p>
              </div>
            )}
          </div>
        );
      case "markets":
        return <MarketIntelligence onOpenStock={(symbol: string) => {
          window.sessionStorage.setItem("finpilot-selected-stock", symbol);
          setActiveView("stocks");
        }} />;
      case "alerts":
        // ✅ SmartAlerts takes NO props
        return <SmartAlerts />;
      default:
        return <Dashboard onViewChange={setActiveView} onToggleChat={() => setIsChatOpen(true)} />;
    }
  };

  // Show loading state
  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen w-full bg-[#040405]">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-400">Loading...</p>
        </div>
     
[truncated — 848 more characters]
```

### server.ts

```typescript
import express from "express";
import path from "path";
import dotenv from "dotenv";
import { createServer as createViteServer } from "vite";
import OpenAI from "openai";
import { GoogleGenAI } from "@google/genai";
import puppeteer from 'puppeteer';
import cors from "cors";
dotenv.config();

const app = express();
app.use(
  cors({
    origin: [
      "http://localhost:5173",
      "http://localhost:3000",
      "https://fintech-ai-wine.vercel.app",
    ],
    methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    credentials: true,
  }),
);

app.options("*", cors());

app.use(express.json());
const PORT = Number(process.env.PORT) || 3000;

// Initialize Groq Client (using the OpenAI SDK wrapper)
const groq = new OpenAI({
  apiKey: process.env.GROQ_API_KEY,
  baseURL: "https://api.groq.com/openai/v1",
});

// Initialize Gemini Client
const ai = new GoogleGenAI({
  apiKey: process.env.GEMINI_API_KEY || "PLACEHOLDER",
  httpOptions: {
    headers: {
      "User-Agent": "aistudio-build",
    },
  },
});

// ===============================
// Finance-Specialized System Prompt
// ===============================
const SYSTEM_PROMPT = `You are FinPilot AI — an elite AI Financial Copilot built for investors, traders, and everyday users who want to master their financial life.

## Your Expertise
You are a specialist in:
- **Personal Finance**: Budgeting, savings strategies, emergency funds, debt management, net worth tracking
- **Expense Analysis**: Spending patterns, category breakdowns, optimization opportunities, subscription audits
- **Stock Markets**: US markets (NYSE, NASDAQ), Indian markets (NSE, BSE), technical analysis, fundamental analysis
- **Investing**: Mutual funds, ETFs, index funds, SIPs, portfolio allocation, diversification strategies
- **Portfolio Analysis**: Risk assessment, Sharpe ratio, beta, sector concentration, rebalancing
- **Financial Planning**: Retirement planning, tax-efficient investing, insurance, estate planning
- **Crypto**: Bitcoin, Ethereum, major cryptocurrencies, DeFi basics, risk considerations
- **Market Intelligence**: Earnings analysis, macroeconomic indicators, sector trends, geopolitical impact
- **Indian Finance**: SEBI regulations, ELSS funds, PPF, NPS, gold bonds, FD rates, UPI, ITR filing tips

## STRICT BOUNDARIES (CRITICAL)
You are strictly a financial agent. If the user asks about ANYTHING other than finance, investing, money, markets, or economics (e.g., coding, cooking recipes, general chatting, sports scores, creative writing, etc.), you MUST decline and respond exactly with:
"I am a specialized financial agent. I can only assist with financial questions. What financial topics would you like to explore?"

Do NOT provide any information on non-financial topics.

## Response Style
- Be concise, clear, and professional — like a Bloomberg analyst meets a trusted advisor
- Use **bold** for key numbers, percentages, and important terms
- Use bullet points for lists and comparisons
- Use markdown tables for comparisons (e.g., stock A vs stock B)
- Format currency clearly: use $ for USD, ₹ for INR
- Always explain financial jargon in plain language
- When discussing investments, always mention relevant risks
- Never guarantee returns or give specific buy/sell signals
- Never recommend illegal financial activities

## Tone
Professional, trustworthy, and educational. Never condescending. Treat the user as a financially curious adult.`;

// ===============================
// Rule-based Custom Demo Responses
// ===============================
function getDemoResponse(userMessage: string): string {
  const query = userMessage.trim().toLowerCase();

  if (
    query.includes("spend") ||
    query.includes("expense") ||
    query.includes("category")
  ) {
    return `### 📊 Expense & Spending Analysis

Based on your transaction data, you have spent a total of **$4,250** so far this month, which is **12% lower** than this time last month! Great job optimizing your budget!

#### 🍕 Top Expense Categories:
| Category | Monthly Spend | Budget Limit | Status |
| :--- | :--- | :--- | :--- |
| **Housing (Rent)** | $2,100 | $2,100 | 🟢 On Track |
| **Dining Out** | $450 | $600 | 🟢 Saved $150 (⬇️ 28% decrease) |
| **Groceries** | $320 | $400 | 🟢 On Track |
| **Utilities** | $280 | $300 | 🟢 On Track |
| **Shopping** | $540 | $400 | 🔴 Over budget by $140 |

#### 💡 Insight and Recommendations:
- **Dining Out Saving**: By reducing restaurant dining, you saved **$150**! Consider routing this directly to your Emergency Fund or systematic investment plan.
- **Shopping Alert**: Shopping is **35% over budget**. Let's review non-essential subscription or impulse buys.

What would you like to explore next? Click an option below or type a custom question!`;
  }

  if (
    query.includes("nvidia") ||
    query.includes("nvda") ||
    query.includes("stock") ||
    query.includes("market")
  ) {
    return `### 📈 Stock Intelligence & NVIDIA (NVDA) Report

**NVIDIA Corporation (NASDAQ: NVDA)** continues to demonstrate incredible financial strength, driven primarily by the sustained global demand for enterprise artificial intelligence chipsets and advanced GPU architectures.

#### 🔍 Key Stock Metrics:
| Metric | Value | Detail / Comparison |
| :--- | :--- | :--- |
| **Current Price** | **$125.50** | Trading within the 52-week range of $75.00 - $140.76 |
| **PE Ratio (TTM)** | **~70.4** | Reflects premium growth expectations relative to sector average (~32.0) |
| **YTD Return** | **+148.3%** | Significantly outperforming the S&P 500 (+14.2%) |
| **Next Earnings** | **Next Week** | Expected revenue growth consensus of +112% YoY |

#### 🚀 Primary Growth Drivers:
1. **AI & Data Center Dominance**: Blackwell architecture demand remains supply-constrained, ensuring high pricing power and fat gross margins (~75%).
2. **Hyperscaler CAPEX**: Major cloud providers (Google, Microsoft, AWS, Meta) continue to expand AI infrastructure budgets.
3. **Software Moat**: CUDA software pla
[truncated — 27361 more characters]
```

### supabaseClient.js

```javascript
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL      // your Project URL
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY  // your anon key

export const supabase = createClient(supabaseUrl, supabaseKey)
```

### index.html

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>#FINPILOT-AI#</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>


```

### fix-jsx.js

```javascript
const fs = require('fs');
let code = fs.readFileSync('src/components/NexusAI.jsx', 'utf8');

// The file has lines that are just `            }` or `          } ` etc.
// Let's replace any `            }\n` with `\n`.

code = code.replace(/^\s*}\s*$/gm, '');
fs.writeFileSync('src/components/NexusAI.jsx', code);

```

### vite.config.ts

```typescript
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import path from "path";
import { defineConfig } from "vite";

export default defineConfig(() => ({
  plugins: [react(), tailwindcss()],

  resolve: {
    alias: {
      "@": path.resolve(__dirname, "."),
    },
  },

  server: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",
        changeOrigin: true,
      },
    },

    hmr: process.env.DISABLE_HMR !== "true",
    watch: process.env.DISABLE_HMR === "true" ? null : {},
  },
}));

```

### src/supabaseClient.js

```javascript
// src/supabaseClient.js
// ONE shared Supabase connection for the whole app.
// Every component imports THIS — never create a second client.
// Why: the client holds the logged-in user's session (their JWT). If you make
// multiple clients, they don't share that session and auth breaks in confusing
// ways. One client = one source of truth for "who is logged in."

import { createClient } from '@supabase/supabase-js'

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY

// Keep the app renderable when a new developer has not created a local .env
// file yet. App.tsx displays a clear setup screen instead of a blank page.
export const isSupabaseConfigured = Boolean(supabaseUrl && supabaseKey)
export const supabase = isSupabaseConfigured ? createClient(supabaseUrl, supabaseKey) : null

```

### src/lib/utils.js

```javascript
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
function cn(...inputs) {
  return twMerge(clsx(inputs));
}
export {
  cn
};

```

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