#!/usr/bin/env python3
"""
Minecraft Username Sniper - Discord Webhook Alerts (Phase 5 Feature #2)

Send snipe results, auth status, and alerts to Discord webhooks.
"""

import httpx
import json
from datetime import datetime, timezone


def send_discord_webhook(url, content=None, title=None, description=None,
                         color=None, fields=None, username="Minecraft Sniper",
                         avatar_url=None):
    """Send a rich embed message to a Discord webhook.

    Args:
        url: Discord webhook URL
        content: Plain text content (above embed)
        title: Embed title
        description: Embed description
        color: Embed color (int, e.g. 0x00FF00 for green)
        fields: List of {"name": str, "value": str, "inline": bool}
        username: Webhook username override
        avatar_url: Webhook avatar URL override

    Returns:
        True if sent successfully, False otherwise
    """
    if not url:
        return False

    embed = {}
    if title:
        embed["title"] = title
    if description:
        embed["description"] = description
    if color is not None:
        embed["color"] = color
    if fields:
        embed["fields"] = fields
    embed["timestamp"] = datetime.now(timezone.utc).isoformat()

    payload = {"embeds": [embed]}
    if content:
        payload["content"] = content
    if username:
        payload["username"] = username
    if avatar_url:
        payload["avatar_url"] = avatar_url

    try:
        resp = httpx.post(url, json=payload, timeout=10.0)
        return resp.status_code in (200, 204)
    except Exception as e:
        print(f"[WEBHOOK] Failed to send: {e}")
        return False


# Color presets
COLOR_SUCCESS = 0x00FF00  # Green
COLOR_FAILURE = 0xFF0000  # Red
COLOR_INFO = 0x0099FF     # Blue
COLOR_WARNING = 0xFFAA00  # Orange


def send_snipe_alert(webhook_url, username, success, account_hash=None,
                     response_time_ms=None, error=None, drop_time=None,
                     mode="exact", threads=10):
    """Send a snipe result alert.

    Args:
        webhook_url: Discord webhook URL
        username: Target Minecraft username
        success: True/False
        account_hash: Hashed account identifier
        response_time_ms: Response time in milliseconds
        error: Error message if failed
        drop_time: Drop time string
        mode: Timing mode
        threads: Thread count used

    Returns:
        True if sent successfully
    """
    color = COLOR_SUCCESS if success else COLOR_FAILURE
    status = "✅ SUCCESS" if success else "❌ FAILED"

    fields = [
        {"name": "Username", "value": f"```{username}```", "inline": True},
        {"name": "Status", "value": status, "inline": True},
        {"name": "Mode", "value": mode, "inline": True},
    ]

    if response_time_ms is not None:
        fields.append({"name": "Response", "value": f"{response_time_ms:.1f}ms", "inline": True})

    if account_hash:
        fields.append({"name": "Account", "value": f"`{account_hash[:8]}`", "inline": True})

    if drop_time:
        fields.append({"name": "Drop Time", "value": drop_time, "inline": True})

    if threads:
        fields.append({"name": "Threads", "value": str(threads), "inline": True})

    if error:
        fields.append({"name": "Error", "value": f"```{error}```", "inline": False})

    return send_discord_webhook(
        url=webhook_url,
        title=f"Snipe Result: {username}",
        description=f"{'Name claimed!' if success else 'Could not claim name.'}",
        color=color,
        fields=fields,
    )


def send_auth_alert(webhook_url, email, success, error=None):
    """Send an authentication status alert."""
    color = COLOR_SUCCESS if success else COLOR_FAILURE
    return send_discord_webhook(
        url=webhook_url,
        title=f"Auth {'Success' if success else 'Failed'}",
        description=f"Account: `{email}`",
        color=color,
        fields=[
            {"name": "Status", "value": "✅ Token obtained" if success else f"❌ {error or 'Unknown error'}", "inline": False},
        ],
    )


def send_info_alert(webhook_url, title, description, fields=None):
    """Send an informational alert."""
    return send_discord_webhook(
        url=webhook_url,
        title=title,
        description=description,
        color=COLOR_INFO,
        fields=fields,
    )


def send_warning_alert(webhook_url, title, description, fields=None):
    """Send a warning alert."""
    return send_discord_webhook(
        url=webhook_url,
        title=title,
        description=description,
        color=COLOR_WARNING,
        fields=fields,
    )


if __name__ == "__main__":
    # Test (requires a webhook URL)
    print("Discord webhook module loaded.")
    print("Usage: send_snipe_alert(webhook_url, 'TestName', True, response_time_ms=150.5)")
