#!/usr/bin/env python3
"""
Test script for AIVA Telegram Escalation System
================================================
Demonstrates human-in-the-loop approval workflow.

IMPORTANT: Set these environment variables before running:
  - TELEGRAM_BOT_TOKEN: Your Telegram bot token from @BotFather
  - TELEGRAM_CHAT_ID: Your Telegram chat ID (get from @userinfobot)

Usage:
    python3 test_telegram_escalation.py

Story: AIVA-Priority-7
"""

import os
import sys
import time
from pathlib import Path

# Add AIVA to path
AIVA_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(AIVA_ROOT))

from notifications.escalation import EscalationManager, UrgencyLevel


def test_create_approval_ticket():
    """Test creating an escalation ticket with Telegram notification."""
    print("=" * 60)
    print("AIVA Telegram Escalation System - Test Script")
    print("=" * 60)
    print()

    # Check environment variables
    bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
    chat_id = os.getenv("TELEGRAM_CHAT_ID")

    if not bot_token or not chat_id:
        print("ERROR: Missing required environment variables:")
        print("  - TELEGRAM_BOT_TOKEN")
        print("  - TELEGRAM_CHAT_ID")
        print()
        print("Setup instructions:")
        print("1. Create bot with @BotFather on Telegram")
        print("2. Get your chat ID from @userinfobot")
        print("3. Set environment variables:")
        print("   export TELEGRAM_BOT_TOKEN='your_token_here'")
        print("   export TELEGRAM_CHAT_ID='your_chat_id_here'")
        sys.exit(1)

    print(f"Bot Token: {bot_token[:20]}...")
    print(f"Chat ID: {chat_id}")
    print()

    # Initialize EscalationManager
    print("Initializing EscalationManager...")
    try:
        manager = EscalationManager(
            telegram_bot_token=bot_token,
            telegram_chat_id=chat_id
        )
        print("✓ EscalationManager initialized")
        print(f"✓ PostgreSQL connection: {'OK' if manager.pg_conn else 'FAILED'}")
        print()
    except Exception as e:
        print(f"✗ Failed to initialize: {e}")
        sys.exit(1)

    # Create test escalation ticket
    print("Creating test escalation ticket...")
    try:
        ticket = manager.escalate(
            decision_id="TEST_DECISION_001",
            reason="Testing AIVA Telegram approval workflow",
            urgency=UrgencyLevel.HIGH.value,
            context={
                "risk_level": "MEDIUM",
                "confidence_score": 0.75,
                "action": "Deploy new model to production",
                "estimated_impact": "High user engagement"
            }
        )
        print("✓ Ticket created successfully")
        print(f"  Ticket ID: {ticket.id}")
        print(f"  Decision ID: {ticket.decision_id}")
        print(f"  Urgency: {ticket.urgency}")
        print(f"  Status: {ticket.status}")
        print(f"  Telegram Message ID: {ticket.telegram_message_id}")
        print()
    except Exception as e:
        print(f"✗ Failed to create ticket: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

    # Check pending escalations
    print("Checking pending escalations...")
    pending = manager.get_pending_escalations()
    print(f"✓ Found {len(pending)} pending ticket(s)")
    for t in pending:
        print(f"  - {t.id}: {t.reason}")
    print()

    print("=" * 60)
    print("CHECK YOUR TELEGRAM")
    print("=" * 60)
    print("You should now see a message with Approve/Reject buttons.")
    print()
    print("To simulate callback handling, use:")
    print(f"  result = manager.handle_callback('approve_{ticket.id}')")
    print(f"  result = manager.handle_callback('reject_{ticket.id}')")
    print()
    print("Or manually resolve:")
    print(f"  result = manager.resolve('{ticket.id}', approved=True, resolver_note='Manual approval')")
    print()

    return ticket.id


def test_manual_resolution(ticket_id: str):
    """Test manual resolution of ticket."""
    print("=" * 60)
    print("Manual Resolution Test")
    print("=" * 60)
    print()

    manager = EscalationManager()

    print(f"Resolving ticket {ticket_id}...")
    try:
        result = manager.resolve(
            ticket_id=ticket_id,
            approved=True,
            resolver_note="Manual approval from test script"
        )
        print("✓ Ticket resolved")
        print(f"  Approved: {result.approved}")
        print(f"  Response time: {result.response_time_seconds} seconds")
        print(f"  Resolved at: {result.resolved_at}")
        print()
    except Exception as e:
        print(f"✗ Failed to resolve: {e}")

    # Check pending again
    print("Checking pending escalations after resolution...")
    pending = manager.get_pending_escalations()
    print(f"✓ Found {len(pending)} pending ticket(s)")
    print()


if __name__ == "__main__":
    # Test creating ticket and sending Telegram
    ticket_id = test_create_approval_ticket()

    # Optionally wait and then auto-resolve
    print("Waiting 5 seconds before auto-resolving...")
    time.sleep(5)

    test_manual_resolution(ticket_id)

    print("=" * 60)
    print("Test complete!")
    print("=" * 60)
