"""Example usage of chat notifications for job events.

This example demonstrates how to use the chat notification system
with the job queue.
"""

from oclawma.notifications import ChatNotificationConfig, NotifyingJobQueue
from oclawma.queue.models import JobPriority


def basic_example():
    """Basic example with Discord notifications."""
    # Configure notifications
    config = ChatNotificationConfig(
        discord_webhook="https://discord.com/api/webhooks/...",
        triggers={
            "on_fail": True,      # Notify on job failure
            "on_complete": True,  # Notify on job completion
            "on_retry": False,    # Don't notify on retries
        },
    )

    # Create queue with notifications
    queue = NotifyingJobQueue(
        "/path/to/queue.db",
        notification_config=config,
    )

    # Enqueue a job (notifications trigger automatically)
    _ = queue.enqueue({"task": "process_data", "file": "data.csv"})

    # Process the job
    def handler(job):
        # Do work here
        print(f"Processing {job.payload}")

    # This will automatically send notifications
    queue.process_next(handler)

    queue.close()


def advanced_example():
    """Advanced example with routing and mentions."""
    config = ChatNotificationConfig(
        # Default Discord webhook
        discord_webhook="https://discord.com/api/webhooks/DEFAULT/...",
        slack_webhook="https://hooks.slack.com/services/...",

        # Enable all triggers
        triggers={
            "on_fail": True,
            "on_complete": True,
            "on_retry": True,
        },

        # Rate limiting (minimum 60 seconds between notifications)
        rate_limit_interval=60.0,

        # Mention user on critical jobs
        mention_on_critical=True,
        discord_user_id="123456789",
        slack_user_id="U123456789",

        # Per-job-type routing
        channel_routing={
            "critical_jobs": {
                "discord_webhook": "https://discord.com/api/webhooks/CRITICAL/...",
            },
            "billing": {
                "slack_webhook": "https://hooks.slack.com/services/BILLING/...",
            },
        },
    )

    queue = NotifyingJobQueue(
        "/path/to/queue.db",
        notification_config=config,
    )

    # This job goes to default channel
    queue.enqueue({"task": "cleanup"}, job_type="maintenance")

    # This job goes to critical channel with @mention
    queue.enqueue(
        {"task": "process_payment"},
        job_type="critical_jobs",
        priority=JobPriority.CRITICAL,
    )

    # This job goes to billing Slack channel
    queue.enqueue(
        {"task": "send_invoice", "amount": 100.00},
        job_type="billing",
    )

    queue.close()


def test_webhooks():
    """Test webhook connectivity."""
    config = ChatNotificationConfig(
        discord_webhook="https://discord.com/api/webhooks/...",
        slack_webhook="https://hooks.slack.com/services/...",
    )

    queue = NotifyingJobQueue(
        ":memory:",
        notification_config=config,
    )

    # Test all configured webhooks
    results = queue.test_notifications()

    for result in results:
        print(f"{result.platform}: {'✅' if result.success else '❌'}")
        print(f"  Status: {result.status_code}")
        print(f"  Latency: {result.latency_ms:.1f}ms")
        if not result.success:
            print(f"  Error: {result.response}")

    queue.close()


def manual_notifications():
    """Example of manually sending notifications."""
    from datetime import datetime

    from oclawma.notifications import ChatNotifier
    from oclawma.queue.models import Job, JobPriority, JobStatus

    config = ChatNotificationConfig(
        discord_webhook="https://discord.com/api/webhooks/...",
        triggers={"on_fail": True, "on_complete": True},
    )

    notifier = ChatNotifier(config)

    # Create a job for testing
    job = Job(
        id=1,
        payload={"task": "test"},
        status=JobStatus.FAILED,
        job_type="test",
        priority=JobPriority.HIGH,
        error="Something went wrong!",
        updated_at=datetime.utcnow(),
    )

    # Send notification manually
    notifier.notify_job_failed(job)

    # Test webhooks
    result = notifier.test_discord_webhook()
    print(f"Discord webhook test: {result.success}")

    notifier.close()


if __name__ == "__main__":
    print("Chat Notifications Example")
    print("=" * 50)
    print()
    print("Run one of the example functions:")
    print("  - basic_example()")
    print("  - advanced_example()")
    print("  - test_webhooks()")
    print("  - manual_notifications()")
