Spaces:
Sleeping

File size: 31,553 Bytes
a845b89
 
bc2284c
429105c
 
 
 
caf2412
 
 
429105c
caf2412
bc2284c
a845b89
dc1ff06
a845b89
bc2284c
caf2412
 
 
 
 
 
 
bc2284c
429105c
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429105c
 
ba63882
 
dc1ff06
ba63882
 
 
 
 
caf2412
 
 
 
 
429105c
caf2412
bc2284c
 
6ba87ee
bc2284c
429105c
caf2412
429105c
 
 
caf2412
 
 
 
 
 
 
bc2284c
 
caf2412
 
a845b89
 
a0ddd3d
 
 
 
 
a845b89
a0ddd3d
a845b89
caf2412
a0ddd3d
 
caf2412
a0ddd3d
a845b89
caf2412
a845b89
 
 
 
 
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
bc2284c
 
dc1ff06
bc2284c
 
429105c
a0ddd3d
caf2412
 
 
429105c
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ba87ee
a845b89
a0ddd3d
caf2412
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
caf2412
 
 
 
a0ddd3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caf2412
 
a0ddd3d
caf2412
 
 
 
 
a0ddd3d
 
caf2412
 
 
 
a0ddd3d
 
caf2412
 
 
 
a0ddd3d
 
caf2412
 
 
 
a0ddd3d
 
 
 
caf2412
a0ddd3d
caf2412
a0ddd3d
 
 
caf2412
 
 
 
a0ddd3d
 
caf2412
 
 
 
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
caf2412
a0ddd3d
caf2412
a0ddd3d
caf2412
 
 
 
a0ddd3d
dc1ff06
caf2412
 
 
 
dc1ff06
a845b89
caf2412
 
 
 
 
 
 
8724320
a845b89
a0ddd3d
caf2412
 
 
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8724320
caf2412
 
 
 
8724320
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
caf2412
a0ddd3d
caf2412
 
a0ddd3d
caf2412
a0ddd3d
caf2412
 
a0ddd3d
8724320
caf2412
 
 
 
 
 
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
 
 
caf2412
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8724320
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a845b89
 
caf2412
 
 
a845b89
 
caf2412
a845b89
 
a0ddd3d
 
 
 
429105c
a845b89
bc2284c
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
a845b89
5915e40
caf2412
 
 
 
a845b89
 
caf2412
 
a845b89
 
caf2412
 
a845b89
caf2412
dc1ff06
a845b89
caf2412
 
 
 
a0ddd3d
caf2412
a0ddd3d
caf2412
e081345
caf2412
a845b89
 
e081345
a845b89
a0ddd3d
 
caf2412
 
 
 
 
a0ddd3d
caf2412
 
a0ddd3d
a845b89
caf2412
a845b89
caf2412
dc1ff06
caf2412
a0ddd3d
a845b89
caf2412
 
 
 
 
 
 
 
a845b89
a0ddd3d
 
caf2412
 
 
 
 
 
 
 
a0ddd3d
a845b89
caf2412
 
 
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a845b89
caf2412
a845b89
caf2412
bc2284c
 
caf2412
 
 
 
 
 
bc2284c
caf2412
 
a845b89
caf2412
5915e40
caf2412
5915e40
caf2412
 
 
 
 
 
 
 
 
 
 
a0ddd3d
429105c
a845b89
 
 
5915e40
caf2412
 
 
a0ddd3d
 
 
 
 
 
 
caf2412
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
 
 
caf2412
a0ddd3d
caf2412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ddd3d
caf2412
 
 
 
 
a0ddd3d
caf2412
 
 
 
e081345
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from supabase import create_client
import google.generativeai as genai
from groq import Groq
import sentry_sdk
from sentry_sdk.integrations.fastapi import FastApiIntegration
from sentry_sdk.integrations.starlette import StarletteIntegration
import os
import re
import logging
from datetime import datetime, timedelta, timezone
from typing import Optional
import traceback

# ─────────────────────────────────────────────
#  LOGGING
# ─────────────────────────────────────────────
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# ─────────────────────────────────────────────
#  SENTRY β€” error monitoring & uptime tracking
#  Add SENTRY_DSN to your Render environment variables.
#  Get a free DSN at https://sentry.io
# ─────────────────────────────────────────────
SENTRY_DSN = os.getenv("SENTRY_DSN")
if SENTRY_DSN:
    sentry_sdk.init(
        dsn=SENTRY_DSN,
        integrations=[
            StarletteIntegration(transaction_style="endpoint"),
            FastApiIntegration(transaction_style="endpoint"),
        ],
        traces_sample_rate=0.2,      # capture 20% of requests for perf tracing
        profiles_sample_rate=0.1,
        environment=os.getenv("ENVIRONMENT", "production"),
        release=os.getenv("RENDER_GIT_COMMIT", "unknown"),
    )
    logger.info("βœ… Sentry initialised")
else:
    logger.warning("⚠️  SENTRY_DSN not set β€” error monitoring disabled")

# ─────────────────────────────────────────────
#  APP INIT
# ─────────────────────────────────────────────
app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://mzfunnel.netlify.app"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ─────────────────────────────────────────────
#  CONFIG
# ─────────────────────────────────────────────
SUPABASE_URL   = os.getenv("SUPABASE_URL")
SUPABASE_KEY   = os.getenv("SUPABASE_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
GROQ_API_KEY   = os.getenv("GROQ_API_KEY")
API_SECRET_KEY = os.getenv("API_SECRET_KEY")

if not all([SUPABASE_URL, SUPABASE_KEY, GEMINI_API_KEY, GROQ_API_KEY, API_SECRET_KEY]):
    raise ValueError("Missing required environment variables")

supabase    = create_client(SUPABASE_URL, SUPABASE_KEY)
genai.configure(api_key=GEMINI_API_KEY)
groq_client = Groq(api_key=GROQ_API_KEY)

# ─────────────────────────────────────────────
#  RATE LIMITING + FREEMIUM GATE
# ─────────────────────────────────────────────
RATE_LIMIT = 10    # requests per WINDOW seconds (burst protection)
WINDOW     = 60    # seconds
FREE_LIMIT = 15    # lifetime free requests per user


def check_rate_limit(client_id: str):
    """Database-backed burst rate limit β€” horizontally scalable."""
    now          = datetime.now(timezone.utc)
    window_start = (now - timedelta(seconds=WINDOW)).isoformat()
    try:
        res = (
            supabase.table("rate_limits")
            .select("id", count="exact")
            .eq("client_id", client_id)
            .gt("created_at", window_start)
            .execute()
        )
        if res.count >= RATE_LIMIT:
            logger.warning(f"Rate limit hit: {client_id}")
            raise HTTPException(
                status_code=429,
                detail="Too many requests. Please wait 60 seconds."
            )
        supabase.table("rate_limits").insert({
            "client_id":  client_id,
            "created_at": now.isoformat()
        }).execute()
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Rate limit check failed (fail-open): {e}")


def check_usage_gate(user_id: str) -> dict:
    """
    Freemium gate β€” 15 lifetime free requests per user.
    Returns usage metadata so the frontend can show a progress bar.
    Raises HTTP 402 when the free limit is exceeded.
    Required Supabase table:
        user_usage (user_id text PK, request_count int, is_premium bool,
                    created_at timestamptz, last_seen timestamptz)
    """
    try:
        res = (
            supabase.table("user_usage")
            .select("request_count, is_premium")
            .eq("user_id", user_id)
            .execute()
        )

        if not res.data:
            # First request β€” create record
            supabase.table("user_usage").insert({
                "user_id":       user_id,
                "request_count": 1,
                "is_premium":    False,
                "created_at":    datetime.now(timezone.utc).isoformat(),
                "last_seen":     datetime.now(timezone.utc).isoformat(),
            }).execute()
            return {"request_count": 1, "is_premium": False,
                    "remaining": FREE_LIMIT - 1, "limit": FREE_LIMIT}

        row        = res.data[0]
        is_premium = row.get("is_premium", False)
        count      = row.get("request_count", 0)

        if not is_premium and count >= FREE_LIMIT:
            raise HTTPException(
                status_code=402,
                detail=f"Free limit of {FREE_LIMIT} analyses reached. Upgrade to continue."
            )

        supabase.table("user_usage").update({
            "request_count": count + 1,
            "last_seen":     datetime.now(timezone.utc).isoformat(),
        }).eq("user_id", user_id).execute()

        remaining = max(0, FREE_LIMIT - (count + 1)) if not is_premium else -1
        return {"request_count": count + 1, "is_premium": is_premium,
                "remaining": remaining, "limit": FREE_LIMIT}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Usage gate failed (fail-open): {e}")
        return {"request_count": 0, "is_premium": False,
                "remaining": FREE_LIMIT, "limit": FREE_LIMIT}


def verify_api_key(x_api_key: str = Header(None)):
    if not x_api_key or x_api_key != API_SECRET_KEY:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return True


# ─────────────────────────────────────────────
#  REQUEST MODELS
# ─────────────────────────────────────────────
class ChatRequest(BaseModel):
    message:      str
    history:      list          = []
    # Per-user context β€” no longer hardcoded
    user_id:      str           = "anonymous"
    location:     Optional[str] = None
    niche:        Optional[str] = None
    budget:       Optional[int] = None
    force_pillar: Optional[int] = None


class ProfileRequest(BaseModel):
    user_id:  str
    location: Optional[str] = None
    niche:    Optional[str] = None
    budget:   Optional[int] = None


# ─────────────────────────────────────────────
#  PER-USER CONTEXT LOADER
# ─────────────────────────────────────────────
def get_user_context(user_id: str, req: ChatRequest) -> dict:
    """
    Priority: request payload β†’ Supabase user_profiles β†’ sensible defaults.
    Required Supabase table:
        user_profiles (user_id text PK, location text, niche text,
                       budget int, updated_at timestamptz)
    """
    defaults = {
        "location": "Lagos, Nigeria",
        "niche":    "local SME market",
        "budget":   500_000,
    }
    try:
        res = (
            supabase.table("user_profiles")
            .select("location, niche, budget")
            .eq("user_id", user_id)
            .execute()
        )
        if res.data:
            p = res.data[0]
            return {
                "location": req.location or p.get("location") or defaults["location"],
                "niche":    req.niche    or p.get("niche")    or defaults["niche"],
                "budget":   req.budget   or p.get("budget")   or defaults["budget"],
            }
    except Exception as e:
        logger.warning(f"Profile load failed for {user_id} (using defaults): {e}")

    return {
        "location": req.location or defaults["location"],
        "niche":    req.niche    or defaults["niche"],
        "budget":   req.budget   or defaults["budget"],
    }


# ─────────────────────────────────────────────
#  4-PILLAR FRAMEWORK OPTIMIZER  (INTERNAL)
#  Framework names are never exposed in API responses.
# ─────────────────────────────────────────────
PILLAR_KEYWORDS = {
    1: ["who", "customer", "student", "buy", "need", "journey",
        "segment", "persona", "audience", "experience", "satisfaction",
        "nps", "retention", "churn", "feedback", "job to be done"],
    2: ["competitor", "market", "threat", "opportunity", "blue ocean",
        "bcg", "growth", "ansoff", "pestle", "porter", "five forces",
        "industry", "rivalry", "substitute", "entry", "swot"],
    3: ["strength", "resource", "vrio", "capability", "operations",
        "value chain", "model", "core competency", "advantage",
        "process", "efficiency", "supply", "logistics", "infrastructure"],
    4: ["revenue", "profit", "cac", "clv", "ltv", "unit economics",
        "tam", "sam", "som", "scale", "roi", "margin", "cost",
        "pricing", "monetise", "monetize", "balanced scorecard", "kpi"],
}

# Internal only β€” never serialised into API responses
_PILLAR_CONFIG = {
    1: {
        "frameworks": ["Audience Segmentation", "Jobs to be Done",
                       "Value Proposition Canvas", "Customer Journey Mapping",
                       "Net Promoter Score", "Product-Market Fit"],
        "goal":    "Mapping customer psychology to product-market alignment",
        "message": "Customer lens active",
    },
    2: {
        "frameworks": ["SWOT Analysis", "PESTLE Analysis", "Porter's Five Forces",
                       "BCG Matrix", "Blue Ocean Strategy", "Ansoff Matrix"],
        "goal":    "Identifying competitive gaps and market positioning opportunities",
        "message": "Market intelligence active",
    },
    3: {
        "frameworks": ["VRIO Analysis", "Core Competencies",
                       "Value Chain Analysis", "Business Model Canvas"],
        "goal":    "Auditing internal capabilities and operational leverage",
        "message": "Capability audit active",
    },
    4: {
        "frameworks": ["Unit Economics & CLV", "TAM-SAM-SOM",
                       "Balanced Scorecard", "Ansoff Matrix"],
        "goal":    "Optimising unit economics and sustainable growth trajectory",
        "message": "Growth engine active",
    },
}


def _score_pillars(query: str) -> dict:
    q = query.lower()
    return {p: sum(1 for kw in kws if kw in q) for p, kws in PILLAR_KEYWORDS.items()}


def optimize_framework_selection(
    has_leads: bool,
    has_inventory: bool,
    user_query: str,
    force_pillar: Optional[int] = None,
) -> dict:
    """
    Selection priority:
      1. force_pillar from frontend (user's explicit choice)
      2. Keyword scoring across all 4 pillars
      3. Hybrid synthesis fallback when no keywords match
    """
    # ── 1. Honour explicit frontend selection ─────────────────────────
    if force_pillar and force_pillar in _PILLAR_CONFIG:
        cfg    = _PILLAR_CONFIG[force_pillar]
        status = (
            ("READY" if has_leads     else "DATA_MISSING") if force_pillar == 1 else
            ("READY" if has_inventory else "PARTIAL")       if force_pillar == 4 else
            "READY"
        )
        logger.info(f"force_pillar={force_pillar} honoured from frontend")
        return {**cfg, "pillar": force_pillar, "status": status}

    # ── 2. Auto keyword scoring ────────────────────────────────────────
    scores      = _score_pillars(user_query)
    best_pillar = max(scores, key=scores.get)
    best_score  = scores[best_pillar]

    # ── 3. Hybrid fallback ─────────────────────────────────────────────
    if best_score == 0:
        dq = (
            "HIGH"   if (has_leads and has_inventory) else
            "MEDIUM" if (has_leads or has_inventory)  else
            "LOW"
        )
        return {
            "pillar": 3, "status": "READY", "data_quality": dq,
            "frameworks": ["Business Model Canvas", "Balanced Scorecard", "Value Chain Analysis"],
            "goal":    "Cross-functional optimisation and strategic resource allocation",
            "message": f"Synthesis mode (Data Quality: {dq})",
        }

    cfg    = _PILLAR_CONFIG[best_pillar]
    status = (
        ("READY" if has_leads     else "DATA_MISSING") if best_pillar == 1 else
        ("READY" if has_inventory else "PARTIAL")       if best_pillar == 4 else
        "READY"
    )
    return {**cfg, "pillar": best_pillar, "status": status}


# ─────────────────────────────────────────────
#  OUTPUT VALIDATION β€” hallucination guardrails
#  Strips any leaked framework names from LLM output
#  and appends financial disclaimers where needed.
# ─────────────────────────────────────────────
_FRAMEWORK_SUBS = {
    r"\bSWOT\b":               "a strategic review",
    r"\bPESTLE\b":             "an environmental scan",
    r"\bVRIO\b":               "a capability assessment",
    r"\bBCG\s*[Mm]atrix\b":   "a portfolio review",
    r"\bAnsoff\b":             "a growth pathway analysis",
    r"\bPorter'?s?\b":         "a competitive structure analysis",
    r"\bJTBD\b":               "a customer needs analysis",
    r"\bTAM[- ]SAM[- ]SOM\b": "a market sizing analysis",
    r"\bNPS\b":                "a loyalty assessment",
    r"\b[Ff]ramework[s]?\b":   "approach",
    r"\b[Mm]atrix\b":          "model",
    r"\b[Cc]anvas\b":          "model",
    r"\bPillar \d\b":          "",
    r"\bP[1-4]\b":             "",
}
_COMPILED_SUBS = {
    re.compile(k, re.IGNORECASE): v for k, v in _FRAMEWORK_SUBS.items()
}

_OVERCONFIDENCE = [
    re.compile(r"(guaranteed|certain|definite)\s+(return|profit|revenue)", re.IGNORECASE),
    re.compile(r"(will definitely|will certainly|100%\s+sure)",            re.IGNORECASE),
]


def validate_output(text: str) -> tuple[str, list]:
    """
    Returns (cleaned_text, list_of_warnings).
    Warnings are logged/sent to Sentry but never exposed to the user.
    """
    warnings = []
    cleaned  = text

    # Strip framework name leakage
    for pattern, replacement in _COMPILED_SUBS.items():
        cleaned = pattern.sub(replacement, cleaned)

    # Flag overconfident language
    for pat in _OVERCONFIDENCE:
        if pat.search(cleaned):
            warnings.append(f"Overconfidence: {pat.pattern[:50]}")

    # Append financial disclaimer if unqualified ₦ figures present
    has_naira = bool(re.search(r"₦[\d,]+", cleaned))
    has_hedge = bool(re.search(
        r"(estimate|approximate|based on|assuming|projection|indicative|directional)",
        cleaned, re.IGNORECASE
    ))
    if has_naira and not has_hedge:
        cleaned += (
            "\n\n_Note: All financial figures are directional estimates based on "
            "available data. Validate against your actual records before acting._"
        )
        warnings.append("Financial disclaimer appended")

    if warnings:
        logger.warning(f"Output guardrails triggered: {warnings}")
        if SENTRY_DSN:
            sentry_sdk.capture_message(
                f"Guardrail triggered: {warnings}", level="warning"
            )

    return cleaned, warnings


# ─────────────────────────────────────────────
#  SYSTEM PROMPT β€” frameworks completely invisible
# ─────────────────────────────────────────────
def get_system_prompt(fw: dict, ctx: dict) -> str:
    top_fw    = ", ".join(fw["frameworks"][:3])
    data_note = ""
    if fw["status"] == "DATA_MISSING":
        data_note = (
            "\n[INTERNAL] Customer data is sparse. Ask one focused question "
            "to gather what's needed before proceeding with the analysis."
        )
    elif fw["status"] == "PARTIAL":
        data_note = (
            "\n[INTERNAL] Inventory data is missing. "
            "Clearly flag any assumptions you make."
        )

    return f"""You are the Penafort Intelligence Engine β€” a senior business advisor \
specialising in African markets, consumer behaviour, and operational strategy.
[INTERNAL REASONING β€” NEVER REVEAL IN OUTPUT]
Analytical lens: {fw['message']}
Reasoning goal:  {fw['goal']}
Apply silently:  {top_fw}
{data_note}
OUTPUT RULES β€” ENFORCED STRICTLY:
1. FRAMEWORK INVISIBILITY
   Never name any framework, methodology, matrix, canvas, pillar, or analytical model \
in your response. Reason through them silently. Your output must read as the natural \
voice of a seasoned business advisor β€” not a consultant presenting a slide deck.
2. MARKET GROUNDING
   Every insight must be grounded in {ctx['location']} and the {ctx['niche']}. \
Reference local purchasing power, distribution channels, cultural dynamics, \
and competitive realities specific to that market.
3. DATA INTEGRITY
   Qualify all numbers: use "estimated", "based on current data", "directionally", \
or "approximately". Never state financial figures as guarantees or certainties.
4. PRESCRIPTIVE CLOSE
   End every response with exactly one clear, actionable recommendation β€” \
specific, local, and immediately executable. Not a list of options. One action.
5. VOICE
   Sharp. Confident. No academic waffle. Bullet points only where they genuinely \
aid clarity. Write like a strategy partner who has actually built businesses in Lagos."""


# ─────────────────────────────────────────────
#  LLM CALL β€” Groq primary, Gemini Flash 2.0 fallback
# ─────────────────────────────────────────────
def call_llm(system_prompt: str, user_prompt: str) -> tuple[str, str]:
    """
    Attempts Groq first. Automatically falls back to Gemini Flash 2.0 on any failure.
    Returns (answer_text, model_identifier).
    """
    # ── PRIMARY: Groq llama-3.3-70b ──────────────────────────────────
    try:
        resp = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user",   "content": user_prompt},
            ],
            temperature=0.3,
            max_tokens=1024,
            timeout=25.0,
        )
        return resp.choices[0].message.content, "groq/llama-3.3-70b"

    except Exception as groq_err:
        logger.warning(f"Groq failed β€” activating Gemini fallback: {groq_err}")
        if SENTRY_DSN:
            sentry_sdk.capture_exception(groq_err)

    # ── FALLBACK: Gemini Flash 2.0 ────────────────────────────────────
    try:
        model = genai.GenerativeModel(
            model_name="gemini-2.0-flash",
            system_instruction=system_prompt,
        )
        resp = model.generate_content(
            user_prompt,
            generation_config=genai.types.GenerationConfig(
                temperature=0.3,
                max_output_tokens=1024,
            ),
        )
        return resp.text, "gemini/flash-2.0"

    except Exception as gemini_err:
        logger.error(f"Gemini fallback also failed: {gemini_err}")
        if SENTRY_DSN:
            sentry_sdk.capture_exception(gemini_err)
        raise HTTPException(
            status_code=502,
            detail="Strategy engine temporarily unavailable. Please try again in a moment."
        )


# ─────────────────────────────────────────────
#  GLOBAL ERROR HANDLER
# ─────────────────────────────────────────────
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"UNHANDLED: {exc}\n{traceback.format_exc()}")
    if SENTRY_DSN:
        sentry_sdk.capture_exception(exc)
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal engine error.", "code": "INTERNAL_SERVER_ERROR"},
    )


# ─────────────────────────────────────────────
#  MAIN CHAT ENDPOINT
# ─────────────────────────────────────────────
@app.post("/chat")
async def chat(req: ChatRequest, x_api_key: str = Header(None)):
    verify_api_key(x_api_key)
    check_rate_limit(x_api_key)

    # Freemium gate β€” raises 402 when free limit exceeded
    usage = check_usage_gate(req.user_id)

    logger.info(
        f"user={req.user_id} | used={usage['request_count']} | "
        f"remaining={usage['remaining']} | premium={usage['is_premium']} | "
        f"force_pillar={req.force_pillar} | msg={req.message[:80]}"
    )

    try:
        # ── 1. Load per-user context ──────────────────────────────────
        ctx = get_user_context(req.user_id, req)

        # ── 2. Fetch live business data ───────────────────────────────
        try:
            leads_res = supabase.table("leads").select("*").execute()
            inv_res   = supabase.table("inventory").select("*").execute()
            leads     = leads_res.data or []
            inventory = inv_res.data or []
        except Exception as e:
            logger.error(f"DB fetch error: {e}")
            raise HTTPException(status_code=503, detail="Knowledge base unreachable.")

        has_leads     = len(leads) > 0
        has_inventory = len(inventory) > 0

        # ── 3. Framework selection (4-pillar, force_pillar honoured) ──
        fw = optimize_framework_selection(
            has_leads, has_inventory, req.message,
            force_pillar=req.force_pillar,
        )
        logger.info(f"Pillar={fw['pillar']} | Status={fw['status']}")

        # ── 4. Vector memory (long-term context) ─────────────────────
        # FIX: corrected model name (should not be changed from this 'models/models/gemini-embedding-2-preview')
        context = ""
        try:
            emb = genai.embed_content(
                model="models/gemini-embedding-2-preview",
                content=req.message,
                task_type="retrieval_query",
            )["embedding"]
            mem = supabase.rpc("match_memories", {
                "query_embedding": emb,
                "match_threshold": 0.3,
                "match_count":     5,
            }).execute()
            context = (
                "\n".join([c["content"] for c in mem.data])[:2000]
                if mem.data else ""
            )
        except Exception as e:
            logger.warning(f"Vector search failed (proceeding without memory): {e}")

        # ── 5. Build prompt ───────────────────────────────────────────
        actual_count = len(leads)
        current_cac  = ctx["budget"] / actual_count if actual_count > 0 else 0
        som_val, sam_val = 2_900, 14_500

        metrics = (
            f"- Leads: {actual_count}\n"
            f"- Inventory items: {len(inventory)}\n"
            f"- Estimated CAC: ₦{int(current_cac):,}\n"
            f"- Budget: ₦{ctx['budget']:,}\n"
            f"- SAM: {sam_val:,} | SOM: {som_val:,}\n"
            f"- Market: {ctx['location']} / {ctx['niche']}"
        )

        history_text = "\n".join(
            [f"{m['role']}: {m['content']}" for m in req.history[-6:]]
        )[:1500]

        user_prompt = (
            f"CONVERSATION HISTORY:\n{history_text}\n\n"
            f"STRATEGIC MEMORY:\n{context}\n\n"
            f"LIVE METRICS:\n{metrics}\n\n"
            f"QUESTION: {req.message}\n\n"
            "Provide expert strategic analysis. End with one clear, actionable recommendation."
        )

        # ── 6. LLM with automatic fallback ───────────────────────────
        raw_answer, model_used = call_llm(get_system_prompt(fw, ctx), user_prompt)
        logger.info(f"LLM response from: {model_used}")

        # ── 7. Validate + strip framework leakage ────────────────────
        answer, guardrail_warnings = validate_output(raw_answer)

        # ── 8. Save to chat_history (powers dashboard) ───────────────
        # Required table: chat_history (user_id, query, response, pillar,
        #                               model, timestamp)
        try:
            supabase.table("chat_history").insert({
                "user_id":   req.user_id,
                "query":     req.message[:500],
                "response":  answer[:1000],
                "pillar":    fw["pillar"],
                "model":     model_used,
                "timestamp": datetime.now(timezone.utc).isoformat(),
            }).execute()
        except Exception as e:
            logger.warning(f"chat_history insert failed: {e}")

        # ── 9. Internal API log ───────────────────────────────────────
        try:
            supabase.table("api_logs").insert({
                "query":      req.message[:500],
                "response":   answer[:500],
                "pillar":     fw["pillar"],
                "model":      model_used,
                "guardrails": str(guardrail_warnings),
                "timestamp":  datetime.now(timezone.utc).isoformat(),
            }).execute()
        except Exception as e:
            logger.warning(f"api_logs insert failed: {e}")

        # ── 10. Response β€” zero framework data exposed externally ─────
        return {
            "status":   "success",
            "response": answer,
            # Usage info for frontend progress bar
            "usage": {
                "requests_used": usage["request_count"],
                "remaining":     usage["remaining"],
                "is_premium":    usage["is_premium"],
                "limit":         FREE_LIMIT,
            },
            # Minimal metadata β€” no framework names, no pillar labels
            "meta": {
                "model":       model_used,
                "data_status": fw["status"],
            },
        }

    except HTTPException as he:
        raise he
    except Exception as e:
        logger.critical(f"Critical failure: {e}")
        if SENTRY_DSN:
            sentry_sdk.capture_exception(e)
        raise HTTPException(
            status_code=500,
            detail="Operational failure in the strategic pipeline."
        )


# ─────────────────────────────────────────────
#  HISTORY ENDPOINT β€” powers the dashboard tab
# ─────────────────────────────────────────────
@app.get("/history/{user_id}")
async def get_history(user_id: str, x_api_key: str = Header(None)):
    verify_api_key(x_api_key)
    try:
        res = (
            supabase.table("chat_history")
            .select("query, response, pillar, model, timestamp")
            .eq("user_id", user_id)
            .order("timestamp", desc=True)
            .limit(50)
            .execute()
        )
        return {"status": "success", "history": res.data or []}
    except Exception as e:
        logger.error(f"History fetch failed: {e}")
        raise HTTPException(status_code=500, detail="Could not load history.")


# ─────────────────────────────────────────────
#  PROFILE ENDPOINT β€” per-user context setup
# ─────────────────────────────────────────────
@app.post("/profile")
async def upsert_profile(req: ProfileRequest, x_api_key: str = Header(None)):
    verify_api_key(x_api_key)
    try:
        supabase.table("user_profiles").upsert({
            "user_id":    req.user_id,
            "location":   req.location,
            "niche":      req.niche,
            "budget":     req.budget,
            "updated_at": datetime.now(timezone.utc).isoformat(),
        }).execute()
        return {"status": "success", "message": "Profile updated."}
    except Exception as e:
        logger.error(f"Profile upsert failed: {e}")
        raise HTTPException(status_code=500, detail="Could not save profile.")


# ─────────────────────────────────────────────
#  HEALTH CHECK
# ─────────────────────────────────────────────
@app.get("/health")
def health():
    return {
        "status":     "healthy",
        "engine":     "Penafort Strategy Engine v3.0",
        "monitoring": "sentry" if SENTRY_DSN else "disabled",
        "timestamp":  datetime.now(timezone.utc).isoformat(),
    }