Spaces:
Runtime error

File size: 6,893 Bytes
d29856e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.orm import Session
from typing import Dict, Any, List
from pydantic import BaseModel
import logging
from datetime import datetime

from db.database import get_db
from db import models, crud
from services import analytics_service
from api.deps import get_current_user

logger = logging.getLogger("BotAnalytics")
router = APIRouter(prefix="/api/v1/bots", tags=["analytics"])

# RESPONSE MODELS
class HealthScoreResponse(BaseModel):
    bot_id: str
    health_score: float
    last_checked: str = None

class KnowledgeGapStatsResponse(BaseModel):
    total_queries: int
    failed_queries: int
    low_confidence_queries: int
    success_rate: float
    avg_confidence: float
    period_days: int

# ============================================================================
# HELPER: Get Bot ID by Public ID with Auth Check
# ============================================================================
def get_bot_id_with_auth(public_id: str, db: Session, current_user: models.User) -> int:
    bot = crud.get_bot_by_public_id(db, public_id)
    if not bot:
        raise HTTPException(status_code=404, detail="Bot not found")
    if bot.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
    return bot.id

# ============================================================================
# COMPREHENSIVE ANALYTICS (DASHBOARD)
# ============================================================================
@router.get("/{public_id}/analytics/comprehensive")
async def get_comprehensive_analytics(
    public_id: str,
    db: Session = Depends(get_db),
    current_user: models.User = Depends(get_current_user)
):
    """
    Get all analytics data in one call.
    """
    bot_id = get_bot_id_with_auth(public_id, db, current_user)
    try:
        data = await analytics_service.get_comprehensive_insights(bot_id, db)
        return data  # Return directly to match frontend interface
    except Exception as e:
        logger.error(f"Dashboard data retrieval failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail="Failed to load dashboard data")

# ============================================================================
# REFRESH INSIGHTS
# ============================================================================
@router.post("/{public_id}/analytics/refresh-insights")
async def refresh_insights(
    public_id: str,
    db: Session = Depends(get_db),
    current_user: models.User = Depends(get_current_user)
):
    """
    Force refresh AI insights.
    """
    bot_id = get_bot_id_with_auth(public_id, db, current_user)
    try:
        # We await this synchronously for the "Refersh" button experience, 
        # or we could make it BG task. 
        # Frontend expects new data back immediately or polling.
        # But smart_insights might be slow (LLM). 
        # Let's try to wait for it since it uses a "spinner" on frontend.
        insights = await analytics_service.get_smart_insights(bot_id, db, force_refresh=True)
        
        # Return full updated dashboard data so frontend can update everything
        data = await analytics_service.get_comprehensive_insights(bot_id, db)
        return data
        
    except Exception as e:
        logger.error(f"Insight refresh failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))

# ============================================================================
# GAP STATISTICS
# ============================================================================
@router.get("/{public_id}/analytics/gaps")
def get_gap_stats(
    public_id: str,
    days: int = 7,
    db: Session = Depends(get_db),
    current_user: models.User = Depends(get_current_user)
):
    bot_id = get_bot_id_with_auth(public_id, db, current_user)
    stats = analytics_service.get_knowledge_gap_stats(bot_id, db, days=days)
    return stats

# ============================================================================
# RESOLVE GAP (ADD KNOWLEDGE)
# ============================================================================
class ResolveGapRequest(BaseModel):
    query: str
    answer: str
    log_id: int | None = None  # Optional, if we want to resolve a specific log entry

@router.post("/{public_id}/analytics/resolve-gap")
async def resolve_gap(
    public_id: str,
    request: ResolveGapRequest,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: models.User = Depends(get_current_user)
):
    """
    Resolve a knowledge gap by adding a Q&A pair and marking logs as resolved.
    """
    bot = crud.get_bot_by_public_id(db, public_id)
    if not bot:
        raise HTTPException(status_code=404, detail="Bot not found")
    
    if bot.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized")
        
    try:
        # 1. Add to Knowledge Base (RAG)
        # Create a Q&A format text
        qa_content = f"Question: {request.query}\nAnswer: {request.answer}"
        filename = f"quick_fix_{request.query[:10].replace(' ', '_')}_{str(datetime.now().timestamp())}.txt"
        
        # We use the RAG pipeline directly to add this 'document'
        from services import rag_pipeline
        success = rag_pipeline.add_document_to_knowledge_base(bot.public_id, qa_content, filename)
        
        if not success:
            raise HTTPException(status_code=500, detail="Failed to add knowledge to vector store")
            
        # 2. Mark specific log as resolved (if provided) or find matching ones
        if request.log_id:
            log = db.query(models.BotAuditLog).filter(models.BotAuditLog.id == request.log_id).first()
            if log:
                log.is_resolved = True
        
        # Also resolve other pending gaps that match this query text exactly
        # This cleans up the "Top Failed" list immediately
        pending_logs = db.query(models.BotAuditLog)\
            .filter(models.BotAuditLog.bot_id == bot.id)\
            .filter(models.BotAuditLog.user_query == request.query)\
            .filter(models.BotAuditLog.flagged_as_gap == True)\
            .filter(models.BotAuditLog.is_resolved == False)\
            .all()
            
        for l in pending_logs:
            l.is_resolved = True
            
        db.commit()
        
        # 3. Recalculate Health Score immediately
        new_score = analytics_service.update_bot_health_if_needed(bot.id, db)
        
        return {
            "status": "success", 
            "message": "Knowledge added and gaps resolved",
            "new_health_score": new_score
        }
        
    except Exception as e:
        logger.error(f"Resolve gap failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))