#!/usr/bin/env python3
"""
Script para testar as estatísticas finais
"""

from src import create_app, db
from src.models import User, Chat, Message, Agente
from src.services.stats_service import StatsService
from datetime import datetime, timedelta
import random

def test_stats_final():
    app = create_app()
    
    with app.app_context():
        try:
            user = User.query.first()
            if not user:
                print("Nenhum usuário encontrado no banco. Crie um usuário primeiro.")
                return
            
            print(f"Usando usuário: {user.username} (ID: {user.id})")
            
            from flask_login import current_user
            import flask_login
            
            class MockUser:
                def __init__(self, user_id):
                    self.id = user_id
                    self.is_authenticated = True
                    self.is_active = True
                    self.is_anonymous = False
                
                def get_id(self):
                    return str(self.id)
            
            original_current_user = flask_login.current_user
            flask_login.current_user = MockUser(user.id)
            
            try:
                total_chats = Chat.query.filter_by(user_id=user.id).count()
                total_messages = Message.query.join(Chat).filter(Chat.user_id == user.id).count()
                messages_with_response_time = Message.query.join(Chat).filter(
                    Chat.user_id == user.id,
                    Message.is_user == False,
                    Message.response_time.isnot(None)
                ).count()
                messages_with_tokens = Message.query.join(Chat).filter(
                    Chat.user_id == user.id,
                    Message.is_user == False,
                    Message.tokens.isnot(None)
                ).count()
                
                print(f"\n=== Dados existentes no banco ===")
                print(f"Total de chats: {total_chats}")
                print(f"Total de mensagens: {total_messages}")
                print(f"Mensagens da IA com response_time: {messages_with_response_time}")
                print(f"Mensagens da IA com tokens: {messages_with_tokens}")
                
                print(f"\n=== Testando StatsService ===")
                stats_data, error = StatsService.get_dashboard_stats(period_days=30)
                
                if error:
                    print(f"Erro ao buscar estatísticas: {error}")
                else:
                    print("Estatísticas obtidas com sucesso:")
                    print(f"- Total de conversas: {stats_data['total_conversations']}")
                    print(f"- Total de mensagens: {stats_data['total_messages']}")
                    print(f"- Tempo médio de resposta: {stats_data['avg_response_time']}s")
                    print(f"- Total de tokens: {stats_data['total_tokens']}")
                    print(f"- Uso por modelo: {stats_data['model_usage']}")
                    print(f"- Dados de atividade: {stats_data['activity_data']}")
                
                if total_chats == 0 or messages_with_response_time == 0:
                    print(f"\n=== Criando dados de teste ===")
                    
                    agent = Agente.query.filter_by(user_id=user.id).first()
                    if not agent:
                        agent = Agente(
                            nome='Agente Teste',
                            descricao='Agente para testes',
                            user_id=user.id,
                            model_identifier='test-model'
                        )
                        db.session.add(agent)
                        db.session.commit()
                        print("Agente de teste criado")
                    
                    chat = Chat(
                        user_id=user.id,
                        agent_id=agent.id,
                        title='Chat de Teste',
                        created_at=datetime.now() - timedelta(days=1)
                    )
                    db.session.add(chat)
                    db.session.commit()
                    
                    user_msg = Message(
                        chat_id=chat.id,
                        message='Olá, como você está?',
                        is_user=True,
                        created_at=chat.created_at + timedelta(minutes=1)
                    )
                    db.session.add(user_msg)
                    
                    ai_msg = Message(
                        chat_id=chat.id,
                        message='Olá! Estou funcionando muito bem, obrigado por perguntar. Como posso ajudá-lo hoje?',
                        is_user=False,
                        created_at=chat.created_at + timedelta(minutes=2),
                        response_time=2.5,  
                        tokens=25  
                    )
                    db.session.add(ai_msg)
                    db.session.commit()
                    
                    print("Dados de teste criados")
                    
                    print(f"\n=== Testando StatsService após criar dados ===")
                    stats_data, error = StatsService.get_dashboard_stats(period_days=30)
                    
                    if not error:
                        print("Estatísticas após criar dados:")
                        print(f"- Total de conversas: {stats_data['total_conversations']}")
                        print(f"- Total de mensagens: {stats_data['total_messages']}")
                        print(f"- Tempo médio de resposta: {stats_data['avg_response_time']}s")
                        print(f"- Total de tokens: {stats_data['total_tokens']}")
                        print(f"- Uso por modelo: {stats_data['model_usage']}")
                    
            finally:
                flask_login.current_user = original_current_user
                    
        except Exception as e:
            print(f"Erro durante o teste: {str(e)}")
            import traceback
            traceback.print_exc()

if __name__ == '__main__':
    test_stats_final() 