#!/usr/bin/env python3
"""
Тест для нового эндпоинта получения детальной информации о событии
"""

import asyncio
import json
import requests
from datetime import datetime

# Конфигурация
API_BASE = "http://localhost:8002"  # Emergency service
USER_SERVICE_BASE = "http://localhost:8001"  # User service

def authenticate_user(username="testuser", password="testpass"):
    """Получаем JWT токен для авторизации"""
    try:
        auth_data = {
            "username": username,
            "password": password
        }
        response = requests.post(f"{USER_SERVICE_BASE}/auth/login", data=auth_data)
        
        if response.status_code == 200:
            token_data = response.json()
            return token_data.get("access_token")
        else:
            print(f"Authentication failed: {response.status_code}")
            print("Response:", response.text)
            return None
            
    except Exception as e:
        print(f"Authentication error: {e}")
        return None

def create_test_emergency():
    """Создаем тестовое событие для проверки"""
    token = authenticate_user()
    if not token:
        return None
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    emergency_data = {
        "latitude": 55.7558,
        "longitude": 37.6176,
        "alert_type": "general",
        "message": "Test emergency for event details API",
        "address": "Test Address, Moscow",
        "contact_emergency_services": True,
        "notify_emergency_contacts": True
    }
    
    try:
        response = requests.post(
            f"{API_BASE}/api/v1/emergency/alerts",
            headers=headers,
            json=emergency_data
        )
        
        if response.status_code == 201:
            alert = response.json()
            event_id = alert.get("id")
            print(f"✅ Created test emergency event with ID: {event_id}")
            return event_id, token
        else:
            print(f"❌ Failed to create emergency: {response.status_code}")
            print("Response:", response.text)
            return None, None
            
    except Exception as e:
        print(f"❌ Error creating emergency: {e}")
        return None, None

def test_event_details(event_id, token):
    """Тестируем получение детальной информации о событии"""
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    print(f"\n🔍 Testing event details for event_id: {event_id}")
    
    try:
        # Тестируем полную детальную информацию
        response = requests.get(
            f"{API_BASE}/api/v1/emergency/events/{event_id}",
            headers=headers
        )
        
        if response.status_code == 200:
            event_details = response.json()
            print("✅ Full event details retrieved successfully!")
            print(f"Event ID: {event_details.get('id')}")
            print(f"Alert Type: {event_details.get('alert_type')}")
            print(f"Status: {event_details.get('status')}")
            print(f"Message: {event_details.get('message')}")
            print(f"Address: {event_details.get('address')}")
            print(f"User: {event_details.get('user', {}).get('username')}")
            print(f"Responses count: {len(event_details.get('responses', []))}")
            print(f"Notifications sent: {event_details.get('notifications_sent', 0)}")
            
        else:
            print(f"❌ Failed to get event details: {response.status_code}")
            print("Response:", response.text)
            
    except Exception as e:
        print(f"❌ Error getting event details: {e}")
    
    try:
        # Тестируем краткую информацию
        response = requests.get(
            f"{API_BASE}/api/v1/emergency/events/{event_id}/brief",
            headers=headers
        )
        
        if response.status_code == 200:
            brief_info = response.json()
            print("\n✅ Brief event info retrieved successfully!")
            print(f"Event ID: {brief_info.get('id')}")
            print(f"Alert Type: {brief_info.get('alert_type')}")
            print(f"Status: {brief_info.get('status')}")
            
        else:
            print(f"\n❌ Failed to get brief event info: {response.status_code}")
            print("Response:", response.text)
            
    except Exception as e:
        print(f"\n❌ Error getting brief event info: {e}")

def respond_to_emergency(event_id, token):
    """Добавляем ответ к событию для проверки responses"""
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    response_data = {
        "response_type": "help_on_way",
        "message": "Test response from API test",
        "eta_minutes": 10
    }
    
    try:
        response = requests.post(
            f"{API_BASE}/api/v1/emergency/events/{event_id}/respond",
            headers=headers,
            json=response_data
        )
        
        if response.status_code == 201:
            print(f"✅ Added response to event {event_id}")
            return True
        else:
            print(f"❌ Failed to add response: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Error adding response: {e}")
        return False

def main():
    print("🚨 Testing Emergency Event Details API")
    print("=" * 50)
    
    # Создаем тестовое событие
    event_id, token = create_test_emergency()
    if not event_id or not token:
        print("❌ Failed to create test emergency. Exiting.")
        return
    
    # Добавляем ответ к событию
    respond_to_emergency(event_id, token)
    
    # Тестируем получение детальной информации
    test_event_details(event_id, token)
    
    print("\n" + "=" * 50)
    print("🎯 Test completed!")
    print(f"Event ID for manual testing: {event_id}")

if __name__ == "__main__":
    main()