# Strategist AI: KPI Architecture & Formula Guide

This document explains exactly how business KPIs are calculated, from the moment a user sends a message to the final dashboard result.

## 1. High-Level Data Flow

The system uses a **Thread-Level Batch Analysis** architecture for maximum accuracy.

```mermaid
graph TD
    A[User/Admin Messages] --> B[Firestore: chat_history]
    A --> C[(Postgres: strategist_feedback)]
    
    D[Analytics Refresh Trigger] --> E[AnalyticsService]
    E -->|1. Find New Threads| C
    E -->|2. Fetch History| B
    E -->|3. AI Batch Analysis| F[Azure OpenAI]
    F -->|4. Store Results| G[(Postgres: strategist_thread_analytics)]
    
    H[Business Dashboard] -->|5. Query Metrics| G
```

---

## 2. Step-by-Step Calculation Flow (Per KPI)

### 🔵 General Metrics
*Calculated from the `strategist_thread_analytics` table.*

1.  **Total Conversations**: A simple `COUNT(*)` of unique `thread_id`s in the analytics table.
2.  **Average Sentiment**: The AI assigns a score (-1 to 1) for the **entire thread**. We then calculate the simple mean (average) of these scores.
3.  **Bot Containment Rate**: 
    -   **AI Logic**: Sets `is_resolved=true` and `escalation_needed=false`.
    -   **Formula**: `(Sessions where resolved=true AND escalation=false) / Total Conversations`.

### 🟢 Customer Intent & Demand
*How we understand what users want.*

1.  **Top Intent Categories**:
    -   **AI Logic**: Categorizes each thread into one of: `pricing`, `support`, `feature_request`, `bug_report`, `general`.
    -   **Calculation**: `GROUP BY intent` and sort by count.
2.  **Lead Qualification Rate**:
    -   **AI Logic**: Flags `is_lead_qualified=true` if the user provided business contact info or specific project requirements.
    -   **Calculation**: `% of total threads where flag is true`.

### 🟡 Conversion Enablement
*Tracking "Strategic Next Steps" (CTAs).*

1.  **CTA Click Rate**:
    -   **AI Logic**: Flags `cta_clicked=true` if the user agreed to a meeting, signed up for a trial, or followed a link suggested by the bot.
    -   **Calculation**: `(Total CTA Clicks / Total Conversations) * 100`.

### 🔴 Voice of the Customer (VOC)
*Direct feedback signals.*

1.  **Pain Point Frequency**: AI extracts specific frustrations. We count every thread where a non-null `pain_point` was identified.
2.  **Objection Trends**: AI identifies reasons for hesitation (e.g., "cost", "security"). We aggregate these keywords.

### 🟣 Helpdesk Performance
*Calculated from the `strategist_tickets` table.*

1.  **Backlog Growth**: Calculates the count of tickets where `status='Open'`.
2.  **Average Resolution Time**: (Placeholder) Measured as the delta between `created_at` and `resolved_at` (when implemented).

---

## 3. How to Individual metrics are defined (AI Prompts)

Every thread is analyzed with the following mandatory JSON schema:

| Field | Meaning | Calculation Logic |
| :--- | :--- | :--- |
| `sentiment_score` | -1.0 to 1.0 | Aggregated mood of all user messages in the thread. |
| `is_high_intent` | boolean | Set to true if the user used words like "urgent", "buy", "quote", or "ASAP". |
| `is_resolved` | boolean | Set to true if the user's final message indicates satisfaction or no further help needed. |
| `intent` | string | Best-fit category for the conversation goal. |

---

## 4. Triggering the Analytics Pipeline

To update these KPIs (e.g., after a day of chats), call the following endpoint:

```http
GET /analytics/refresh?tenant_id=<id>
```

This will:
1.  Scan for any `thread_id` in `strategist_feedback` that hasn't been analyzed yet.
2.  Perform a batch analysis for each.
3.  Refresh the KPI aggregates.
