File size: 12,018 Bytes
6075b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b287c8
ac0b137
6075b99
 
 
 
 
 
 
5b287c8
6075b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b287c8
 
6075b99
 
 
 
 
ac0b137
5b287c8
 
ac0b137
 
5b287c8
ac0b137
 
 
 
 
 
 
 
6075b99
 
 
 
 
 
 
 
 
ac0b137
6075b99
 
 
 
 
5b287c8
6075b99
 
 
 
 
 
 
 
 
5b287c8
 
 
 
 
 
6075b99
 
 
5b287c8
 
 
 
6075b99
 
 
 
 
5b287c8
6075b99
 
 
 
 
5b287c8
6075b99
 
5b287c8
6075b99
 
 
 
 
5b287c8
6075b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b287c8
 
6075b99
 
 
 
 
 
 
 
 
 
 
 
5b287c8
6075b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b287c8
6075b99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b287c8
6075b99
 
 
 
 
 
 
 
 
 
483f29e
 
 
 
 
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
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime
from typing import List, Dict, Any
import logging

from auth import get_current_user
from models import (
    AnalysisRequest, AnalysisResponse, InsightResponse, QueryRequest, QueryResponse,
    MarketIntelligenceRequest, MarketIntelligenceResponse, GeneratePlanRequest, GeneratePlanResponse,
    TrendRequest, TrendResponse, UserSignup, UserLogin, UserProfile, SubscriptionPlan
)
from reddit_client import RedditClient
from analyzer import call_groq_for_insight
from serp_client import get_search_volume, search_competitors, search_funding_news
from supabase_client import supabase_auth, supabase_db
from config import GROQ_MODEL, GROQ_API_KEY, SUPABASE_JWT_SECRET

# Groq client is imported in analyzer
# Reddit client
reddit_client = RedditClient()

app = FastAPI(title="Founder Intelligence Engine API", version="2.0")

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

logger = logging.getLogger(__name__)

# ====================== Root ======================
@app.get("/")
async def root():
    return {"message": "Founder Intelligence Engine API is running"}

# ====================== Auth Endpoints ======================
@app.post("/auth/signup", response_model=UserProfile)
async def signup(user: UserSignup):
    try:
        # 1. Create auth user (using anon client)
        response = supabase_auth.auth.sign_up({
            "email": user.email,
            "password": user.password,
            "options": {"data": {"full_name": user.full_name}}
        })
        user_data = response.user

        # 2. Check if profile already exists (using service client to bypass RLS)
        existing = supabase_db.table("profiles").select("*").eq("id", user_data.id).execute()
        if not existing.data:
            # Create profile record
            supabase_db.table("profiles").insert({
                "id": user_data.id,
                "email": user_data.email,
                "full_name": user.full_name,
                "subscription_tier": "free",
                "subscription_status": "active"
            }).execute()

        # 3. Return profile
        return UserProfile(
            id=user_data.id,
            email=user_data.email,
            full_name=user.full_name,
            subscription_tier="free",
            subscription_status="active",
            created_at=user_data.created_at
        )
    except Exception as e:
        # If the user already exists in auth but not in profiles, we can still return a helpful message
        raise HTTPException(status_code=400, detail=str(e))

@app.post("/auth/login")
async def login(creds: UserLogin):
    try:
        response = supabase_auth.auth.sign_in_with_password({
            "email": creds.email,
            "password": creds.password
        })
        return {"access_token": response.session.access_token, "token_type": "bearer"}
    except Exception as e:
        raise HTTPException(status_code=401, detail="Invalid credentials")

@app.get("/auth/me", response_model=UserProfile)
async def get_me(user=Depends(get_current_user)):
    # user already contains profile info from the token validation
    # but we can fetch fresh profile from DB if needed
    profile = supabase_db.table("profiles").select("*").eq("id", user["id"]).execute()
    if not profile.data:
        raise HTTPException(status_code=404, detail="Profile not found")
    p = profile.data[0]
    return UserProfile(
        id=user["id"],
        email=user["email"],
        full_name=p["full_name"],
        subscription_tier=p["subscription_tier"],
        subscription_status=p["subscription_status"],
        created_at=p["created_at"]
    )

# ====================== Subscription Plans ======================
@app.get("/plans", response_model=List[SubscriptionPlan])
async def list_plans():
    plans = supabase_db.table("plans").select("*").execute()
    return [SubscriptionPlan(**p) for p in plans.data]

# ====================== Helper: Check subscription limits ======================
def check_subscription_limit(user_id: str, requested_posts: int):
    """Raise 403 if user exceeds plan limits."""
    profile = supabase_db.table("profiles").select("subscription_tier").eq("id", user_id).execute()
    tier = profile.data[0]["subscription_tier"] if profile.data else "free"
    # Fetch plan features
    plan = supabase_db.table("plans").select("features").eq("name", tier.capitalize()).execute()
    if plan.data:
        features = plan.data[0]["features"]
        posts_limit = features.get("posts_per_month", 10)  # default free limit
        # Count posts this month for this user
        start_of_month = datetime.now().replace(day=1, hour=0, minute=0, second=0).isoformat()
        count_res = supabase_db.table("insights").select("id", count="exact").eq("user_id", user_id).gte("created_at", start_of_month).execute()
        current_count = count_res.count if hasattr(count_res, 'count') else 0
        if current_count + requested_posts > posts_limit:
            raise HTTPException(status_code=403, detail=f"Monthly post limit of {posts_limit} reached. Upgrade your plan.")
    # else no limit

# ====================== Analysis Endpoints ======================
@app.post("/analyze", response_model=AnalysisResponse)
async def analyze(request: AnalysisRequest, user=Depends(get_current_user)):
    user_id = user["id"]
    total_posts = len(request.subreddits) * request.posts_per_subreddit
    check_subscription_limit(user_id, total_posts)

    all_results = []
    for sub in request.subreddits:
        posts = reddit_client.get_top_posts(sub, limit=request.posts_per_subreddit, time_filter=request.time_filter)
        for post in posts:
            text = f"Title: {post.get('title','')}\nBody: {post.get('selftext','')[:1500]}"
            insight = call_groq_for_insight(text)
            # Compute opportunity score
            pain = insight.get("problem_severity_score", 5)
            timing = insight.get("market_timing_score", 5)
            rev = len(insight.get("revenue_opportunity", "")) / 20
            comp = 10 - len(insight.get("competitor_weakness", "")) / 20
            opp_score = int((pain + timing + rev + comp) / 4 * 10)
            insight["opportunity_score"] = min(100, max(0, opp_score))

            result = {
                "user_id": user_id,
                "subreddit": sub,
                "post_title": post.get("title"),
                "post_url": post.get("url"),
                "timestamp": datetime.utcnow().isoformat(),
                "insight_data": insight,
                "opportunity_score": insight["opportunity_score"]
            }
            # Insert into Supabase using service client
            supabase_db.table("insights").insert(result).execute()
            all_results.append({
                "subreddit": sub,
                "post_title": post.get("title"),
                "post_url": post.get("url"),
                "timestamp": result["timestamp"],
                "model": GROQ_MODEL,
                "insight": insight
            })
    return AnalysisResponse(status="success", message=f"Analyzed {len(all_results)} posts", insights=all_results)

@app.get("/insights", response_model=List[InsightResponse])
async def get_insights(user=Depends(get_current_user)):
    res = supabase_db.table("insights").select("*").eq("user_id", user["id"]).order("created_at", desc=True).execute()
    insights = []
    for row in res.data:
        insights.append(InsightResponse(
            id=row["id"],
            subreddit=row["subreddit"],
            post_title=row["post_title"],
            post_url=row["post_url"],
            timestamp=row["timestamp"],
            model=GROQ_MODEL,
            insight=row["insight_data"]
        ))
    return insights

# ====================== Query / RAG ======================
@app.post("/query", response_model=QueryResponse)
async def query_insights(request: QueryRequest, user=Depends(get_current_user)):
    insights = supabase_db.table("insights").select("*").eq("user_id", user["id"]).execute()
    relevant = []
    for row in insights.data:
        data = row["insight_data"]
        text = f"{data.get('burning_pain','')} {data.get('startup_idea','')} {data.get('customer_type','')}"
        if request.query.lower() in text.lower():
            relevant.append(row)
    if not relevant:
        relevant = sorted(insights.data, key=lambda x: x["opportunity_score"], reverse=True)[:request.n_results]
    else:
        relevant = relevant[:request.n_results]

    if not relevant:
        raise HTTPException(status_code=404, detail="No relevant insights found")

    context = "\n\n".join([f"From r/{r['subreddit']}: {r['insight_data'].get('burning_pain','')} {r['insight_data'].get('startup_idea','')}" for r in relevant])
    from groq import Groq
    groq = Groq(api_key=GROQ_API_KEY)
    try:
        response = groq.chat.completions.create(
            model=GROQ_MODEL,
            messages=[
                {"role": "system", "content": "You are a startup advisor. Use the provided Reddit insights to answer the user's question concisely."},
                {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {request.query}"}
            ],
            temperature=0.5
        )
        answer = response.choices[0].message.content
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Groq error: {e}")
    sources = [{"title": r["post_title"], "subreddit": r["subreddit"], "url": r["post_url"]} for r in relevant]
    return QueryResponse(answer=answer, sources=sources)

# ====================== Market Intelligence ======================
@app.post("/market-intelligence", response_model=MarketIntelligenceResponse)
async def market_intelligence(request: MarketIntelligenceRequest, user=Depends(get_current_user)):
    interest = get_search_volume(request.idea)
    competitors = search_competitors(request.idea)
    news = search_funding_news(request.idea)
    return MarketIntelligenceResponse(
        interest_score=interest,
        competitors=competitors,
        funding_news=news
    )

# ====================== Startup Builder ======================
@app.post("/generate-plan", response_model=GeneratePlanResponse)
async def generate_plan(request: GeneratePlanRequest, user=Depends(get_current_user)):
    from groq import Groq
    groq = Groq(api_key=GROQ_API_KEY)
    prompt = f"""Based on the following startup insight, generate:
- MVP Plan (key features for first version)
- Product Architecture (high-level tech stack)
- Go-to-Market Strategy (channels, pricing)
- Unique Moat (competitive advantage)
- Risk Assessment (legal, technical, market)
Insight: {request.insight}
"""
    try:
        response = groq.chat.completions.create(
            model=GROQ_MODEL,
            messages=[{"role": "user", "content": prompt}],
            temperature=0.6
        )
        plan = response.choices[0].message.content
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Groq error: {e}")
    return GeneratePlanResponse(plan=plan)

# ====================== Trends ======================
@app.get("/trends", response_model=TrendResponse)
async def trends(subreddit: str = None, user=Depends(get_current_user)):
    query = supabase_db.table("insights").select("timestamp", "subreddit").eq("user_id", user["id"])
    if subreddit:
        query = query.eq("subreddit", subreddit)
    res = query.execute()
    from collections import defaultdict
    data = defaultdict(int)
    for row in res.data:
        date = row["timestamp"].split("T")[0]
        data[date] += 1
    dates = sorted(data.keys())
    counts = [data[d] for d in dates]
    return TrendResponse(dates=dates, counts=counts)

@app.get("/test")
async def test():
    return {"test": "ok"}