File size: 24,651 Bytes
30e08c6
 
 
 
 
 
 
 
630c616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b167b1a
 
 
 
 
630c616
 
 
 
 
 
 
 
30e08c6
630c616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e08c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630c616
30e08c6
630c616
 
30e08c6
630c616
 
 
30e08c6
630c616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30e08c6
 
 
630c616
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import streamlit as st
import pandas as pd
import numpy as np
import os
from datetime import datetime, timedelta, date
import time
import io
import base64
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta, date
import time
import json
import google.generativeai as genai
from google.generativeai.types import HarmCategory, HarmBlockThreshold


# Setup AI Services
def setup_genai():
    """Initialize and configure Google's Generative AI and list available models"""
    try:
        # Try getting API key from Streamlit secrets first
        if 'GOOGLE_API_KEY' in st.secrets:
            api_key = st.secrets['GOOGLE_API_KEY']
        # Fall back to environment variable
        elif 'GOOGLE_API_KEY' in os.environ:
            api_key = os.environ['GOOGLE_API_KEY']
        else:
            st.warning("Google API key not found. Using simulated AI responses.")
            st.session_state.gemini_model = "gemini-1.5-pro"
            return False
            
        genai.configure(api_key=api_key)

# Import pages
from pages.dashboard-page import render_financial_dashboard, get_runway_analysis, get_fundraising_readiness_analysis
from pages.decision-simulator import render_decision_simulator, get_decision_analysis
from pages.fund-monitoring import render_fund_monitoring, get_fraud_analysis
from pages.financial-advisor import render_ai_financial_advisor, get_advisory_guidance, generate_voice_response
from pages.book-session import render_book_session

# Initialize page configuration
st.set_page_config(
    page_title="StartupFinancePilot",
    page_icon="๐Ÿ’ฐ",
    layout="wide",
    initial_sidebar_state="expanded"
)


# Initialize session state variables
if 'booked_sessions' not in st.session_state:
    st.session_state.booked_sessions = []
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []
if 'audio_response' not in st.session_state:
    st.session_state.audio_response = None
if 'insights_cache' not in st.session_state:
    st.session_state.insights_cache = {}
if 'gemini_model' not in st.session_state:
    st.session_state.gemini_model = None
if 'current_page' not in st.session_state:
    st.session_state.current_page = "Financial Dashboard"
    
from pages.dashboard import render_financial_dashboard
from pages.decision_simulator import render_decision_simulator
from pages.fund_monitoring import render_fund_monitoring
from pages.advisor import render_ai_financial_advisor

# Constants
DEFAULT_GROWTH_RATE = 0.08  # 8% monthly growth
DEFAULT_BURN_RATE = 85000   # $85,000 monthly burn
ENGINEER_SALARY = 10000     # $10,000 monthly cost per engineer ($120K/year)

# Initialize session state variables
if 'startups' not in st.session_state:
    st.session_state.startups = {}  # Dictionary to store multiple startup data
if 'current_startup' not in st.session_state:
    st.session_state.current_startup = None  # Currently selected startup
if 'current_page' not in st.session_state:
    st.session_state.current_page = 'upload'  # Default page
if 'insights_cache' not in st.session_state:
    st.session_state.insights_cache = {}

def switch_page(page_name):
    """Function to switch between pages"""
    st.session_state.current_page = page_name
    st.rerun()

# Page config
st.set_page_config(
    page_title="StartupFinancePilot",
    page_icon="๐Ÿ’ฐ",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS
st.markdown("""
<style>
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    .stDeployButton {display:none;}
    
    .main-header {
        font-size: 2.5rem;
        color: #0066cc;
        margin-bottom: 0.5rem;
    }
    .sub-header {
        font-size: 1.5rem;
        color: #5c5c5c;
        margin-bottom: 1.5rem;
    }
    .metric-card {
        background-color: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .metric-label {
        font-size: 1rem;
        color: #5c5c5c;
    }
    .metric-value {
        font-size: 1.8rem;
        color: #0066cc;
        font-weight: bold;
    }
    .good-metric {
        color: #28a745;
    }
    .warning-metric {
        color: #ffc107;
    }
    .danger-metric {
        color: #dc3545;
    }
    
    /* Style for sidebar buttons */
    div.stButton > button {
        width: 100%;
        padding: 10px 10px;
        border: none;
        background-color: #E6F3FF;
        color: #0066cc;
        border-radius: 10px;
        text-align: left;
        margin: 5px 0;
        font-weight: bold;
    }
    
    div.stButton > button:hover {
        background-color: #CCE5FF;
        color: #004080;
    }
    
    /* Style for title box */
    .title-box {
        background: linear-gradient(45deg, #0066cc, #66b3ff);
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 20px;
        text-align: center;
        color: white;
        cursor: pointer;
    }
</style>
""", unsafe_allow_html=True)

# Sample data
def load_sample_data():
    """Load sample data for demonstration"""
    # TechHealth AI data
    startup_data = {
        "name": "TechHealth AI",
        "stage": "Seed",
        "founded": "18 months ago",
        "employees": 12,
        "last_funding": "$1.2M seed round 10 months ago",
        "cash": 320000,
        "burn_rate": 85000,
        "revenue": 15000,
        "growth_rate": 0.08
    }
    
    # Cash flow history
    cash_flow_data = {
        "Month": [f"Month {i}" for i in range(1, 11)],
        "Revenue": [8000, 8500, 9200, 10000, 10800, 11700, 12600, 13600, 14700, 15800],
        "Payroll": [60000, 60000, 62000, 62000, 65000, 65000, 70000, 70000, 75000, 75000],
        "Marketing": [8000, 9000, 10000, 12000, 15000, 18000, 15000, 12000, 10000, 8000],
        "Office": [5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000],
        "Software": [3000, 3200, 3500, 3800, 4000, 4200, 4500, 4800, 5000, 5200],
        "Travel": [2000, 1800, 2500, 3000, 4000, 4500, 3500, 3000, 2500, 2000],
        "Legal": [1500, 1000, 800, 1200, 800, 2000, 1500, 1000, 3000, 1200],
        "Misc": [1000, 1200, 1300, 1500, 1700, 1800, 2000, 2200, 2500, 2800]
    }
    
    # Add calculated fields
    df = pd.DataFrame(cash_flow_data)
    df["Total_Expenses"] = df[["Payroll", "Marketing", "Office", "Software", "Travel", "Legal", "Misc"]].sum(axis=1)
    df["Net_Burn"] = df["Total_Expenses"] - df["Revenue"]
    
    # Transaction data
    transactions = pd.DataFrame([
        {"Date": "2023-11-05", "Category": "Travel", "Vendor": "Caribbean Cruises", "Amount": 8500, "Description": "Team Retreat Planning", "Flag": "Suspicious"},
        {"Date": "2023-11-12", "Category": "Marketing", "Vendor": "LuxuryGifts Inc", "Amount": 4200, "Description": "Client Appreciation", "Flag": "Suspicious"},
        {"Date": "2023-11-22", "Category": "Office", "Vendor": "Premium Furniture", "Amount": 12000, "Description": "Office Upgrades", "Flag": "Suspicious"},
        {"Date": "2023-11-28", "Category": "Consulting", "Vendor": "Strategic Vision LLC", "Amount": 7500, "Description": "Strategy Consulting", "Flag": "Suspicious"},
        {"Date": "2023-12-05", "Category": "Software", "Vendor": "Personal Apple Store", "Amount": 3200, "Description": "Development Tools", "Flag": "Suspicious"},
        {"Date": "2023-12-12", "Category": "Legal", "Vendor": "Anderson Brothers", "Amount": 5800, "Description": "Legal Services", "Flag": "Normal"},
        {"Date": "2023-12-20", "Category": "Payroll", "Vendor": "November Payroll", "Amount": 75000, "Description": "Monthly Payroll", "Flag": "Normal"},
        {"Date": "2023-12-22", "Category": "Marketing", "Vendor": "Google Ads", "Amount": 8000, "Description": "Ad Campaign", "Flag": "Normal"},
        {"Date": "2023-12-25", "Category": "Office", "Vendor": "WeWork", "Amount": 5000, "Description": "Monthly Rent", "Flag": "Normal"},
        {"Date": "2023-12-28", "Category": "Software", "Vendor": "AWS", "Amount": 5200, "Description": "Cloud Services", "Flag": "Normal"}
    ])
    
    return startup_data, df, transactions

# Parse CSV file to dataframe
def parse_csv_to_df(file):
    """Parse uploaded CSV file to Pandas DataFrame"""
    try:
        df = pd.read_csv(file)
        return df, None
    except Exception as e:
        return None, f"Error parsing CSV: {e}"

# Upload and process financial data files
def render_upload_page():
    """Render the upload page for startup data"""
    st.markdown("<h1 class='main-header'>Upload Your Startup Data</h1>", unsafe_allow_html=True)
    st.markdown("<p class='sub-header'>Upload CSV files or use sample data to get started</p>", unsafe_allow_html=True)
    
    with st.expander("Upload Instructions", expanded=False):
        st.markdown("""
        ### How to Upload Your Startup Data
        
        You can upload three types of files:
        
        1. **Company Profile** - A CSV with basic information about your startup including:
           - name, stage, founded, employees, last_funding, cash, burn_rate, revenue, growth_rate
        
        2. **Cash Flow Data** - A CSV with monthly cash flow data with columns:
           - Month, Revenue, Payroll, Marketing, Office, Software, Travel, Legal, Misc
        
        3. **Transaction Data** - A CSV with transaction details:
           - Date, Category, Vendor, Amount, Description, Flag
           
        If you don't have these files ready, you can use our sample data.
        """)
    
    col1, col2 = st.columns(2)
    
    with col1:
        startup_name = st.text_input("Startup Name", value="My Startup")
        
        profile_file = st.file_uploader("Upload Company Profile (CSV)", type=['csv'])
        cash_flow_file = st.file_uploader("Upload Cash Flow Data (CSV)", type=['csv'])
        transactions_file = st.file_uploader("Upload Transactions Data (CSV)", type=['csv'])
    
    with col2:
        st.markdown("""
        <div style="background-color: #f0f7ff; padding: 15px; border-radius: 10px; height: 90%;">
            <h4>Why Upload Your Data?</h4>
            <p>By uploading your actual financial data, you'll get:</p>
            <ul>
                <li>Personalized AI insights tailored to your startup</li>
                <li>Accurate runway projections based on your real spending patterns</li>
                <li>Custom recommendations to optimize your burn rate</li>
                <li>More realistic decision simulations</li>
            </ul>
            <p>All data is processed securely and never stored permanently.</p>
        </div>
        """, unsafe_allow_html=True)
    
    # Process the files if uploaded
    if st.button("Process Data"):
        # Initialize with default values
        startup_data = {
            "name": startup_name,
            "stage": "Seed",
            "founded": "12 months ago",
            "employees": 5,
            "last_funding": "Not specified",
            "cash": 100000,
            "burn_rate": 20000,
            "revenue": 5000,
            "growth_rate": 0.05
        }
        
        cash_flow_df = None
        transactions_df = None
        
        # Parse company profile
        if profile_file:
            try:
                profile_df, error = parse_csv_to_df(profile_file)
                if error:
                    st.error(error)
                else:
                    # Get the first row as a dictionary
                    if len(profile_df) > 0:
                        startup_data.update(profile_df.iloc[0].to_dict())
                        st.success(f"Successfully loaded company profile for {startup_data['name']}")
            except Exception as e:
                st.error(f"Error processing company profile: {e}")
        
        # Parse cash flow data
        if cash_flow_file:
            cash_flow_df, error = parse_csv_to_df(cash_flow_file)
            if error:
                st.error(error)
            else:
                # Add calculated fields if not present
                if "Total_Expenses" not in cash_flow_df.columns:
                    expense_columns = [col for col in cash_flow_df.columns if col not in ["Month", "Revenue", "Total_Expenses", "Net_Burn"]]
                    cash_flow_df["Total_Expenses"] = cash_flow_df[expense_columns].sum(axis=1)
                
                if "Net_Burn" not in cash_flow_df.columns:
                    cash_flow_df["Net_Burn"] = cash_flow_df["Total_Expenses"] - cash_flow_df["Revenue"]
                
                st.success("Successfully loaded cash flow data")
        
        # Parse transactions data
        if transactions_file:
            transactions_df, error = parse_csv_to_df(transactions_file)
            if error:
                st.error(error)
            else:
                # Ensure transactions data has required columns
                required_columns = ["Date", "Category", "Vendor", "Amount", "Description"]
                if all(col in transactions_df.columns for col in required_columns):
                    if "Flag" not in transactions_df.columns:
                        transactions_df["Flag"] = "Normal"  # Default flag
                    
                    st.success("Successfully loaded transactions data")
                else:
                    st.error("Transactions file is missing required columns")
        
        # If any files were processed, save the data to session state
        if profile_file or cash_flow_file or transactions_file:
            if cash_flow_df is None:
                # Create a sample cash flow dataframe if none was uploaded
                cash_flow_data = {
                    "Month": [f"Month {i}" for i in range(1, 7)],
                    "Revenue": [startup_data['revenue'] * (1 + startup_data['growth_rate'])**i for i in range(6)],
                    "Payroll": [startup_data['burn_rate'] * 0.7] * 6,
                    "Marketing": [startup_data['burn_rate'] * 0.15] * 6,
                    "Office": [startup_data['burn_rate'] * 0.05] * 6,
                    "Software": [startup_data['burn_rate'] * 0.03] * 6,
                    "Travel": [startup_data['burn_rate'] * 0.02] * 6,
                    "Legal": [startup_data['burn_rate'] * 0.01] * 6,
                    "Misc": [startup_data['burn_rate'] * 0.04] * 6
                }
                cash_flow_df = pd.DataFrame(cash_flow_data)
                cash_flow_df["Total_Expenses"] = cash_flow_df[["Payroll", "Marketing", "Office", "Software", "Travel", "Legal", "Misc"]].sum(axis=1)
                cash_flow_df["Net_Burn"] = cash_flow_df["Total_Expenses"] - cash_flow_df["Revenue"]
            
            if transactions_df is None:
                # Create a sample transactions dataframe if none was uploaded
                transactions_data = {
                    "Date": [(datetime.now() - timedelta(days=i*5)).strftime("%Y-%m-%d") for i in range(10)],
                    "Category": ["Payroll", "Marketing", "Office", "Software", "Travel", "Legal", "Misc", "Payroll", "Marketing", "Office"],
                    "Vendor": ["Payroll Provider", "Facebook Ads", "Office Rent", "AWS", "Travel Agency", "Legal Firm", "Miscellaneous", "Payroll Provider", "Google Ads", "Office Supplies"],
                    "Amount": [startup_data['burn_rate'] * 0.7, startup_data['burn_rate'] * 0.15, startup_data['burn_rate'] * 0.05, startup_data['burn_rate'] * 0.03, startup_data['burn_rate'] * 0.02, startup_data['burn_rate'] * 0.01, startup_data['burn_rate'] * 0.04, startup_data['burn_rate'] * 0.7, startup_data['burn_rate'] * 0.15, startup_data['burn_rate'] * 0.05],
                    "Description": ["Monthly Payroll", "Ad Campaign", "Monthly Rent", "Cloud Services", "Business Travel", "Legal Services", "Miscellaneous Expenses", "Monthly Payroll", "Ad Campaign", "Office Supplies"],
                    "Flag": ["Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal", "Normal"]
                }
                transactions_df = pd.DataFrame(transactions_data)
            
            # Store in session state
            st.session_state.startups[startup_data['name']] = {
                'profile': startup_data,
                'cash_flow': cash_flow_df,
                'transactions': transactions_df
            }
            
            # Set as current startup
            st.session_state.current_startup = startup_data['name']
            
            st.success(f"Successfully added {startup_data['name']} to your startups")
            st.info("You can now analyze this startup's data in the dashboard")
            
            # Redirect to dashboard
            switch_page('dashboard')
    
    # Sample data options
    st.subheader("Or Use Sample Data")
    
    sample_col1, sample_col2 = st.columns(2)
    
    with sample_col1:
        if st.button("Use TechHealth AI Sample"):
            # Load sample data
            startup_data, cash_flow_df, transactions_df = load_sample_data()
            
            # Store in session state
            st.session_state.startups["TechHealth AI"] = {
                'profile': startup_data,
                'cash_flow': cash_flow_df,
                'transactions': transactions_df
            }
            
            # Set as current startup
            st.session_state.current_startup = "TechHealth AI"
            
            st.success("Successfully loaded TechHealth AI sample data")
            # Redirect to dashboard
            switch_page('dashboard')
    
    with sample_col2:
        if st.button("Use Custom Sample"):
            # Create a custom sample
            startup_data = {
                "name": "GreenTech Innovations",
                "stage": "Series A",
                "founded": "3 years ago",
                "employees": 25,
                "last_funding": "$4.5M Series A 8 months ago",
                "cash": 2800000,
                "burn_rate": 220000,
                "revenue": 75000,
                "growth_rate": 0.12
            }
            
            # Sample cash flow data
            cash_flow_data = {
                "Month": [f"Month {i}" for i in range(1, 11)],
                "Revenue": [45000, 48000, 52000, 57000, 62000, 66000, 70000, 72000, 74000, 75000],
                "Payroll": [140000, 142000, 145000, 150000, 160000, 165000, 175000, 180000, 185000, 190000],
                "Marketing": [25000, 28000, 30000, 32000, 35000, 32000, 30000, 28000, 26000, 25000],
                "Office": [12000, 12000, 12000, 12000, 12000, 12000, 12000, 12000, 12000, 12000],
                "Software": [8000, 8500, 9000, 9500, 10000, 10500, 11000, 11500, 12000, 12500],
                "Travel": [5000, 6000, 7000, 8000, 7000, 6000, 5000, 6000, 7000, 8000],
                "Legal": [4000, 3000, 3500, 2500, 3000, 4000, 3500, 3000, 2500, 3000],
                "Misc": [3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500]
            }
            
            cash_flow_df = pd.DataFrame(cash_flow_data)
            cash_flow_df["Total_Expenses"] = cash_flow_df[["Payroll", "Marketing", "Office", "Software", "Travel", "Legal", "Misc"]].sum(axis=1)
            cash_flow_df["Net_Burn"] = cash_flow_df["Total_Expenses"] - cash_flow_df["Revenue"]
            
            # Sample transaction data
            transactions_df = pd.DataFrame([
                {"Date": "2023-11-10", "Category": "Travel", "Vendor": "First Class Flights", "Amount": 12000, "Description": "Executive Retreat", "Flag": "Suspicious"},
                {"Date": "2023-11-18", "Category": "Marketing", "Vendor": "VIP Events Co", "Amount": 18000, "Description": "Investor Dinner", "Flag": "Suspicious"},
                {"Date": "2023-12-01", "Category": "Office", "Vendor": "Luxury Furniture", "Amount": 25000, "Description": "Executive Office Upgrade", "Flag": "Suspicious"},
                {"Date": "2023-12-15", "Category": "Legal", "Vendor": "Premium Law Group", "Amount": 35000, "Description": "Legal Consultation", "Flag": "Normal"},
                {"Date": "2023-12-20", "Category": "Payroll", "Vendor": "December Payroll", "Amount": 190000, "Description": "Monthly Payroll", "Flag": "Normal"}
            ])
            
            # Store in session state
            st.session_state.startups["GreenTech Innovations"] = {
                'profile': startup_data,
                'cash_flow': cash_flow_df,
                'transactions': transactions_df
            }
            
            # Set as current startup
            st.session_state.current_startup = "GreenTech Innovations"
            
            st.success("Successfully loaded GreenTech Innovations sample data")
            # Redirect to dashboard
            switch_page('dashboard')

# Create sidebar navigation
def create_sidebar():
    with st.sidebar:
        # Title box that works as home button
        st.markdown("""
            <div class="title-box" onclick="window.location.href='#'">
                <h1>๐Ÿ’ฐ StartupFinancePilot</h1>
                <p>AI-powered financial assistant for startups</p>
            </div>
        """, unsafe_allow_html=True)

        # Startup selector (if there are startups in the session state)
        if st.session_state.startups:
            st.subheader("Selected Startup")
            startup_names = list(st.session_state.startups.keys())
            selected_startup = st.selectbox(
                "Choose Startup", 
                startup_names,
                index=startup_names.index(st.session_state.current_startup) if st.session_state.current_startup in startup_names else 0
            )
            st.session_state.current_startup = selected_startup
            
            # Show basic startup info
            if selected_startup in st.session_state.startups:
                startup_data = st.session_state.startups[selected_startup]['profile']
                st.markdown(f"""
                **Stage:** {startup_data['stage']}  
                **Cash:** ${startup_data['cash']:,}  
                **Monthly Burn:** ${startup_data['burn_rate']:,}  
                **Monthly Revenue:** ${startup_data['revenue']:,}  
                """)

        st.markdown("<hr>", unsafe_allow_html=True)  # Divider
        
        # Upload data button at the top
        if st.button("๐Ÿ“ค Upload Startup Data", use_container_width=True):
            switch_page('upload')

        # Navigation buttons
        if st.button("๐Ÿ“Š Financial Dashboard", use_container_width=True):
            switch_page('dashboard')
            
        if st.button("๐Ÿ”ฎ Decision Simulator", use_container_width=True):
            switch_page('simulator')
            
        if st.button("๐Ÿ•ต๏ธ Fund Monitoring", use_container_width=True):
            switch_page('monitoring')
            
        if st.button("๐Ÿค– AI Financial Advisor", use_container_width=True):
            switch_page('advisor')


def main():
    # Load sample data
    startup_data, cash_flow_df, transactions_df = load_sample_data()
    
    # Create sidebar
    st.sidebar.title("StartupFinancePilot")
    st.sidebar.image("https://img.freepik.com/premium-vector/business-finance-analytics-logo-design-vector-template_67715-552.jpg", width=150)
    
    # Company profile
    st.sidebar.header("Company Profile")
    st.sidebar.write(f"**{startup_data['name']}**")
    st.sidebar.write(f"Stage: {startup_data['stage']}")
    st.sidebar.write(f"Founded: {startup_data['founded']}")
    st.sidebar.write(f"Employees: {startup_data['employees']}")
    st.sidebar.write(f"Last Funding: {startup_data['last_funding']}")
    
    
    # Navigation
    st.sidebar.header("Navigation")
    pages = {
        "Financial Dashboard": render_financial_dashboard,
        "Decision Simulator": render_decision_simulator,
        "Fund Monitoring": render_fund_monitoring,
        "AI Financial Advisor": render_ai_financial_advisor,
        "Book a Session": render_book_session
    }
    
    # Page selection
    selected_page = st.sidebar.radio("Go to", list(pages.keys()))
    st.session_state.current_page = selected_page
    
    # Render selected page
    if selected_page == "Financial Dashboard":
        pages[selected_page](startup_data, cash_flow_df)
    elif selected_page == "Decision Simulator":
        pages[selected_page](startup_data)
    elif selected_page == "Fund Monitoring":
        pages[selected_page](transactions_df)
    elif selected_page == "AI Financial Advisor":
        pages[selected_page](startup_data)
    else:  # Book a Session
        pages[selected_page]()

if __name__ == "__main__":
    main()