#!/usr/bin/env python3
"""Test CalDAV integration for automatic meeting scheduling."""

import os
import sys
from datetime import datetime, timedelta
from dotenv import load_dotenv

# Load environment
load_dotenv()

def main():
    print("🧪 Test integracji CalDAV\n")
    print("=" * 60)
    
    return run_tests()


def run_tests():
    """Run all CalDAV tests."""

# Test 1: Check if CalDAV is enabled
print("\n1️⃣  Sprawdzanie konfiguracji CalDAV...")
caldav_enabled = os.getenv('CALDAV_ENABLED', 'false').lower() == 'true'
print(f"   CALDAV_ENABLED: {caldav_enabled}")

if not caldav_enabled:
    print("\n⚠️  CalDAV jest wyłączone. Ustaw CALDAV_ENABLED=true w .env aby kontynuować.")
    exit(0)

print(f"   CALDAV_URL: {os.getenv('CALDAV_URL', 'NOT SET')}")
print(f"   CALDAV_USERNAME: {os.getenv('CALDAV_USERNAME', 'NOT SET')}")
print(f"   CALDAV_CALENDAR: {os.getenv('CALDAV_CALENDAR', 'Calendar')}")

# Test 2: Import and create client
print("\n2️⃣  Tworzenie klienta CalDAV...")
try:
    from llmass.calendar import CalendarClient
    client = CalendarClient()
    
    if client.is_available():
        print("   ✅ Klient CalDAV połączony")
    else:
        print("   ❌ Klient CalDAV niedostępny")
        exit(1)
except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

# Test 3: Get events
print("\n3️⃣  Pobieranie wydarzeń z kalendarza...")
try:
    now = datetime.now()
    events = client.get_events(now, now + timedelta(days=7))
    print(f"   ✅ Znaleziono {len(events)} wydarzeń w ciągu najbliższych 7 dni")
    
    if events:
        print("\n   Przykładowe wydarzenia:")
        for i, event in enumerate(events[:3], 1):
            print(f"   {i}. {event['summary']}")
            print(f"      {event['start'].strftime('%Y-%m-%d %H:%M')} - {event['end'].strftime('%H:%M')}")
except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

# Test 4: Find free slots
print("\n4️⃣  Wyszukiwanie wolnych terminów...")
try:
    slots = client.find_free_slots(
        duration_minutes=30,
        days_ahead=7,
        work_start="09:00",
        work_end="17:00",
        exclude_weekends=True
    )
    print(f"   ✅ Znaleziono {len(slots)} wolnych slotów (30 min)")
    
    if slots:
        print("\n   Pierwsze 3 wolne sloty:")
        for i, (start, end) in enumerate(slots[:3], 1):
            day_name = ['Pon', 'Wt', 'Śr', 'Czw', 'Pt', 'Sob', 'Nd'][start.weekday()]
            print(f"   {i}. {day_name}, {start.strftime('%d.%m.%Y, %H:%M')} - {end.strftime('%H:%M')}")
    else:
        print("   ⚠️  Brak wolnych slotów")
except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

# Test 5: Test meeting detection
print("\n5️⃣  Test wykrywania próśb o spotkanie...")
try:
    from llmass.calendar import detect_meeting_request, extract_meeting_preferences
    
    test_emails = [
        {
            'lang': 'pl',
            'email': {
                'subject': 'Zapytanie o spotkanie',
                'body': 'Witam, chciałbym umówić się na 30-minutowe spotkanie w przyszłym tygodniu.'
            }
        },
        {
            'lang': 'en',
            'email': {
                'subject': 'Meeting Request',
                'body': 'Hello, can we schedule a meeting next week?'
            }
        },
        {
            'lang': 'de',
            'email': {
                'subject': 'Terminanfrage',
                'body': 'Guten Tag, können wir einen Termin vereinbaren?'
            }
        }
    ]
    
    for test in test_emails:
        is_meeting = detect_meeting_request(test['email'], test['lang'])
        print(f"\n   [{test['lang'].upper()}] '{test['email']['subject']}'")
        print(f"       Wykryto prośbę: {'✅ TAK' if is_meeting else '❌ NIE'}")
        
        if is_meeting:
            prefs = extract_meeting_preferences(test['email'], test['lang'])
            print(f"       Długość: {prefs.get('duration', 'nie wykryto')} min")
            print(f"       Pilne: {'TAK' if prefs.get('urgent') else 'NIE'}")
            if prefs.get('preferred_days'):
                print(f"       Preferowane dni: {', '.join(prefs['preferred_days'])}")

except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

# Test 6: Test slot formatting
print("\n6️⃣  Test formatowania propozycji terminów...")
try:
    from llmass.calendar import format_slot_proposal
    
    if slots:
        test_slots = slots[:3]
        
        for lang in ['pl', 'en', 'de', 'fr']:
            formatted = format_slot_proposal(test_slots, lang)
            print(f"\n   [{lang.upper()}]:")
            print("   " + "\n   ".join(formatted.split('\n')[:4]))  # First 4 lines
    else:
        print("   ⚠️  Brak slotów do formatowania")
        
except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

# Test 7: Test booking manager
print("\n7️⃣  Test menedżera bookingów...")
try:
    from llmass.calendar import BookingManager
    
    booking_mgr = BookingManager()
    print("   ✅ BookingManager utworzony")
    
    # Store test proposal
    test_sender = "test@example.com"
    test_subject = "Test Meeting"
    if slots:
        test_slots = slots[:3]
        key = booking_mgr.store_proposed_slots(test_sender, test_subject, test_slots)
        print(f"   ✅ Zapisano propozycję: {key}")
        
        # Retrieve proposal
        proposal = booking_mgr.get_proposed_slots(test_sender, test_subject)
        if proposal:
            print(f"   ✅ Odczytano propozycję: {len(proposal['slots'])} slotów")
        
        # Cleanup
        booking_mgr.cleanup_old_proposals(days_old=0)  # Don't actually delete our test
    
except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

# Test 8: Test slot selection parsing
print("\n8️⃣  Test parsowania wyboru terminu...")
try:
    from llmass.calendar import parse_slot_selection
    
    test_bodies = [
        ("Termin 1 mi odpowiada", 0),
        ("I choose option 2", 1),
        ("The second slot works for me", 1),
        ("Opcja 3 jest ok", 2),
    ]
    
    if slots:
        test_slots = slots[:3]
        for body, expected in test_bodies:
            result = parse_slot_selection(body, test_slots)
            status = "✅" if result == expected else "❌"
            print(f"   {status} '{body}' -> slot {result} (oczekiwano {expected})")
    
except Exception as e:
    print(f"   ❌ Błąd: {e}")
    exit(1)

    # Summary
    print("\n" + "=" * 60)
    print("✅ Wszystkie testy zakończone pomyślnie!")
    print("\n💡 System jest gotowy do automatycznego umawiania terminów!")
    print("\n📝 Aby przetestować z prawdziwymi emailami:")
    print("   ./run_llmass.sh write --limit 3 --dry-run")
    print("\n" + "=" * 60)
    return 0


if __name__ == "__main__":
    sys.exit(main())
