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
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
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Any

# --- Brainstorm Class ---
class BrainstormManager:
    def __init__(self):
        # Initialize session state for products
        if 'products' not in st.session_state:
            st.session_state.products = {}

# --- Data Processing Class ---
class DataProcessor:
    def __init__(self):
        self.data = None
        self.numeric_columns = []
        self.categorical_columns = []
        self.date_columns = []
    
    def load_data(self, file) -> bool:
        try:
            self.data = pd.read_csv(file)
            self._classify_columns()
            return True
        except Exception as e:
            st.error(f"Error loading data: {str(e)}")
            return False
    
    def _classify_columns(self):
        for col in self.data.columns:
            if pd.api.types.is_numeric_dtype(self.data[col]):
                self.numeric_columns.append(col)
            elif pd.api.types.is_datetime64_any_dtype(self.data[col]):
                self.date_columns.append(col)
            else:
                try:
                    pd.to_datetime(self.data[col])
                    self.date_columns.append(col)
                except:
                    self.categorical_columns.append(col)

    def get_basic_stats(self) -> Dict[str, Any]:
        if self.data is None:
            return {}
        
        stats = {
            'summary': self.data[self.numeric_columns].describe(),
            'missing_values': self.data.isnull().sum(),
            'row_count': len(self.data),
            'column_count': len(self.data.columns)
        }
        return stats

    def create_visualization(self, chart_type: str, x_col: str, y_col: str, color_col: str = None) -> go.Figure:
        if chart_type == "Line Plot":
            fig = px.line(self.data, x=x_col, y=y_col, color=color_col)
        elif chart_type == "Bar Plot":
            fig = px.bar(self.data, x=x_col, y=y_col, color=color_col)
        elif chart_type == "Scatter Plot":
            fig = px.scatter(self.data, x=x_col, y=y_col, color=color_col)
        elif chart_type == "Box Plot":
            fig = px.box(self.data, x=x_col, y=y_col, color=color_col)
        else:
            fig = px.histogram(self.data, x=x_col, color=color_col)
        
        return fig

# --- Sample Data Generation ---
def generate_sample_data():
    dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
    return pd.DataFrame({
        'Date': dates,
        'Revenue': np.random.normal(1000, 100, len(dates)),
        'Users': np.random.randint(100, 200, len(dates)),
        'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
        'Category': np.random.choice(['A', 'B', 'C'], len(dates))
    })

# --- Page Rendering Functions ---
def render_dashboard():
    st.header("πŸ“Š Performance Dashboard")
    data = generate_sample_data()
    
    # KPI Metrics
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        st.metric("Total Revenue", f"${data['Revenue'].sum():,.2f}")
    with col2:
        st.metric("Total Users", f"{data['Users'].sum():,}")
    with col3:
        st.metric("Avg Engagement", f"{data['Engagement'].mean():.2%}")
    with col4:
        st.metric("Active Days", len(data))
    
    # Charts
    col1, col2 = st.columns(2)
    with col1:
        st.subheader("Revenue Trend")
        fig = px.line(data, x='Date', y='Revenue')
        st.plotly_chart(fig, use_container_width=True)
    
    with col2:
        st.subheader("User Engagement by Category")
        fig = px.scatter(data, x='Date', y='Engagement', 
                        size='Users', color='Category')
        st.plotly_chart(fig, use_container_width=True)

def render_analytics():
    st.header("πŸ” Data Analytics")
    
    processor = DataProcessor()
    
    # File upload
    uploaded_file = st.file_uploader("Upload your CSV data", type=['csv'])
    
    if uploaded_file is not None:
        if processor.load_data(uploaded_file):
            st.success("Data loaded successfully!")
            
            tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"])
            
            # Data Preview Tab
            with tabs[0]:
                st.subheader("Data Preview")
                st.dataframe(processor.data.head())
                st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}")
            
            # Statistics Tab
            with tabs[1]:
                st.subheader("Basic Statistics")
                stats = processor.get_basic_stats()
                st.write(stats['summary'])
                
                st.subheader("Missing Values")
                st.write(stats['missing_values'])
            
            # Visualization Tab
            with tabs[2]:
                st.subheader("Create Visualization")
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    chart_type = st.selectbox(
                        "Select Chart Type",
                        ["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"]
                    )
                
                with col2:
                    x_col = st.selectbox("Select X-axis", processor.data.columns)
                
                with col3:
                    y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None
                
                color_col = st.selectbox("Select Color Variable (optional)", 
                                       ['None'] + processor.categorical_columns)
                color_col = None if color_col == 'None' else color_col
                
                fig = processor.create_visualization(
                    chart_type,
                    x_col,
                    y_col if y_col else x_col,
                    color_col
                )
                st.plotly_chart(fig, use_container_width=True)
            
            # Metrics Tab
            with tabs[3]:
                st.subheader("Column Metrics")
                selected_col = st.selectbox("Select column", processor.numeric_columns)
                
                metrics = {
                    'Mean': processor.data[selected_col].mean(),
                    'Median': processor.data[selected_col].median(),
                    'Std Dev': processor.data[selected_col].std(),
                    'Min': processor.data[selected_col].min(),
                    'Max': processor.data[selected_col].max()
                }
                
                cols = st.columns(len(metrics))
                for col, (metric, value) in zip(cols, metrics.items()):
                    col.metric(metric, f"{value:.2f}")



        
    def generate_product_form(self) -> Dict:
        """Generate dynamic form fields for product input"""
        with st.form("product_form"):
            basic_info = {
                "name": st.text_input("Product Name"),
                "category": st.selectbox("Category", ["Digital", "Physical", "Service"]),
                "description": st.text_area("Description"),
                "target_audience": st.multiselect("Target Audience", 
                    ["Students", "Professionals", "Businesses", "Seniors", "Youth"]),
                "price_range": st.slider("Price Range ($)", 0, 1000, (50, 200)),
                "launch_date": st.date_input("Expected Launch Date")
            }
            
            st.subheader("Market Analysis")
            market_analysis = {
                "competitors": st.text_area("Main Competitors (one per line)"),
                "unique_features": st.text_area("Unique Selling Points"),
                "market_size": st.selectbox("Market Size", 
                    ["Small", "Medium", "Large", "Enterprise"]),
                "growth_potential": st.slider("Growth Potential", 1, 10)
            }
            
            submitted = st.form_submit_button("Save Product")
            return basic_info, market_analysis, submitted

    def analyze_product(self, product_data: Dict) -> Dict:
        """Generate insights based on product data"""
        insights = {
            "market_opportunity": self._calculate_opportunity_score(product_data),
            "suggested_price": self._suggest_price(product_data),
            "risk_factors": self._identify_risks(product_data),
            "next_steps": self._generate_next_steps(product_data)
        }
        return insights

    def _calculate_opportunity_score(self, data: Dict) -> int:
        score = 0
        if data.get("market_size") == "Large":
            score += 3
        if len(data.get("target_audience", [])) >= 2:
            score += 2
        if data.get("growth_potential", 0) > 7:
            score += 2
        return min(score, 10)

    def _suggest_price(self, data: Dict) -> float:
        base_price = sum(data.get("price_range", (0, 0))) / 2
        if data.get("market_size") == "Enterprise":
            base_price *= 1.5
        return round(base_price, 2)

    def _identify_risks(self, data: Dict) -> List[str]:
        risks = []
        if data.get("competitors"):
            risks.append("Competitive market - differentiation crucial")
        if len(data.get("target_audience", [])) < 2:
            risks.append("Narrow target audience - consider expansion")
        return risks

    def _generate_next_steps(self, data: Dict) -> List[str]:
        steps = [
            "Create detailed product specification",
            "Develop MVP timeline",
            "Plan marketing strategy"
        ]
        if data.get("market_size") == "Enterprise":
            steps.append("Prepare enterprise sales strategy")
        return steps

def render_brainstorm_page():
    st.title("Product Brainstorm Hub")
    manager = BrainstormManager()
    
    # View/Create toggle
    action = st.sidebar.radio("Action", ["View Products", "Create New Product"])
    
    if action == "Create New Product":
        basic_info, market_analysis, submitted = manager.generate_product_form()
        
        if submitted:
            # Combine form data
            product_data = {**basic_info, **market_analysis}
            
            # Generate insights
            insights = manager.analyze_product(product_data)
            
            # Store product
            product_id = f"prod_{len(st.session_state.products)}"
            st.session_state.products[product_id] = {
                "data": product_data,
                "insights": insights,
                "created_at": str(datetime.datetime.now())
            }
            
            st.success("Product added! View insights in the Products tab.")
    
    else:
        if st.session_state.products:
            for prod_id, product in st.session_state.products.items():
                with st.expander(f"🎯 {product['data']['name']}"):
                    col1, col2 = st.columns(2)
                    
                    with col1:
                        st.subheader("Product Details")
                        st.write(f"Category: {product['data']['category']}")
                        st.write(f"Target: {', '.join(product['data']['target_audience'])}")
                        st.write(f"Description: {product['data']['description']}")
                    
                    with col2:
                        st.subheader("Insights")
                        st.metric("Opportunity Score", f"{product['insights']['market_opportunity']}/10")
                        st.metric("Suggested Price", f"${product['insights']['suggested_price']}")
                        
                        st.write("**Risk Factors:**")
                        for risk in product['insights']['risk_factors']:
                            st.write(f"- {risk}")
                        
                        st.write("**Next Steps:**")
                        for step in product['insights']['next_steps']:
                            st.write(f"- {step}")
        else:
            st.info("No products yet. Create one to get started!")

# Usage in main app
if __name__ == "__main__":
    render_brainstorm_page()

def render_chat():
    st.header("πŸ’¬ Business Assistant")
    
    # Initialize chat history
    if "messages" not in st.session_state:
        st.session_state.messages = []
    
    # Display chat history
    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])
    
    # Chat input
    if prompt := st.chat_input("Ask about your business..."):
        st.session_state.messages.append({"role": "user", "content": prompt})
        with st.chat_message("user"):
            st.markdown(prompt)
        
        # Simple response (placeholder for LLM integration)
        response = f"Thank you for your question about '{prompt}'. The LLM integration will be implemented soon."
        
        with st.chat_message("assistant"):
            st.markdown(response)
        st.session_state.messages.append({"role": "assistant", "content": response})


#main file
def main():
    st.set_page_config(
        page_title="Prospira",
        page_icon="πŸ“Š",
        layout="wide",
        initial_sidebar_state="expanded"
    )
    
    with st.sidebar:
        st.title("Prospira")
        st.subheader("Data-Driven Solutions")
        
        page = st.radio(
            "Navigation",
            ["Dashboard", "Analytics", "Brainstorm", "Chat"]
        )
    
    if page == "Dashboard":
        render_dashboard()
    elif page == "Analytics":
        render_analytics()
    elif page == "Brainstorm":
        render_brainstorm_page()
    elif page == "Chat":
        render_chat()

if __name__ == "__main__":
    main()