Spaces:
Sleeping

File size: 4,420 Bytes
de547ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Operations Copilot analytics endpoint.

GET /api/copilot?admin_key=    — scorecards + per-call rows + reservation count
GET /api/call-summary          — public; latest call_log for a table (post-call card)
"""

from __future__ import annotations

import time
from collections import Counter
from datetime import datetime, timezone
from typing import Optional

from fastapi import APIRouter, Query

import config
from store import get_store

router = APIRouter(prefix="/api", tags=["copilot"])

_cache: dict = {"data": None, "ts": 0}
CACHE_TTL = 60  # seconds


def _build_analytics() -> dict:
    store = get_store()
    call_logs = store.list_call_logs(limit=200)
    orders = store.list_orders()

    total_calls = len(call_logs)
    successful_orders = sum(1 for o in orders if o.get("status") not in ("", None))
    order_totals = [o.get("total_amount", 0) or 0 for o in orders if o.get("total_amount")]
    avg_order_value = round(sum(order_totals) / len(order_totals), 2) if order_totals else 0
    total_revenue = sum(order_totals)

    # Orders placed today
    today = datetime.now(timezone.utc).date().isoformat()
    orders_today = sum(1 for o in orders if (o.get("created_at") or "").startswith(today))

    # Extraction-derived metrics
    upsell_count = sum(1 for c in call_logs if c.get("upsell_accepted") is True)
    escalation_count = sum(1 for c in call_logs if c.get("human_escalation") is True)
    calls_with_extractions = sum(1 for c in call_logs if c.get("extractions") is not None)

    sentiment_counts: Counter = Counter()
    language_counts: Counter = Counter()
    for c in call_logs:
        if c.get("sentiment"):
            sentiment_counts[c["sentiment"].lower()] += 1
        if c.get("customer_language"):
            language_counts[c["customer_language"].lower()] += 1

    top_language = language_counts.most_common(1)[0][0].title() if language_counts else "—"
    extraction_coverage = round(calls_with_extractions / total_calls * 100, 1) if total_calls else 0

    # Most recent call for system health
    last_webhook_ts = call_logs[0].get("created_at") if call_logs else None

    pending_reservations = len(store.list_reservations(status="pending"))

    return {
        "scorecards": {
            "total_calls": total_calls,
            "successful_orders": successful_orders,
            "avg_order_value": avg_order_value,
            "total_revenue": total_revenue,
            "orders_today": orders_today,
            "upsell_count": upsell_count,
            "upsell_rate": round(upsell_count / total_calls * 100, 1) if total_calls else 0,
            "escalation_count": escalation_count,
            "escalation_rate": round(escalation_count / total_calls * 100, 1) if total_calls else 0,
            "top_language": top_language,
            "sentiment_counts": dict(sentiment_counts),
            "language_counts": dict(language_counts),
        },
        "system_health": {
            "extraction_coverage_pct": extraction_coverage,
            "calls_with_extractions": calls_with_extractions,
            "last_webhook_ts": last_webhook_ts,
            "bolna_agent_id": config.BOLNA_AGENT_ID or None,
            "webhook_configured": bool(config.BOLNA_AGENT_ID),
        },
        "pending_reservations": pending_reservations,
        "calls": call_logs,
    }


@router.get("/copilot")
async def copilot(admin_key: str = Query(default="")):
    if config.ADMIN_KEY and admin_key != config.ADMIN_KEY:
        return {"success": False, "message": "Invalid admin key."}
    now = time.time()
    if _cache["data"] is None or now - _cache["ts"] > CACHE_TTL:
        _cache["data"] = _build_analytics()
        _cache["ts"] = now
    return {"success": True, **_cache["data"]}


@router.get("/call-summary")
async def call_summary(
    table_number: str = Query(...),
    outlet_location: str = Query(default=config.DEFAULT_OUTLET),
):
    log = get_store().latest_call_log(table_number, outlet_location)
    if not log:
        return {"success": False, "found": False}
    return {
        "success": True,
        "found": True,
        "summary": log.get("summary"),
        "sentiment": log.get("sentiment"),
        "customer_language": log.get("customer_language"),
        "special_requests": log.get("special_requests"),
        "upsell_accepted": log.get("upsell_accepted"),
        "confidence_score": log.get("confidence_score"),
    }