"""Discord embed formatters for peon-mcp events.

Each builder returns a plain dict matching Discord's embed object schema.
No discord.py import is required — the dict is sent directly via the REST API.
"""

from __future__ import annotations

from datetime import datetime, timezone

# Discord embed colors
COLOR_GREEN = 0x57F287   # task.created
COLOR_GOLD = 0xFEE75C    # task.completed, feature.completed
COLOR_RED = 0xED4245     # task.failed
COLOR_ORANGE = 0xE67E22  # task.timeout
# Priority badge emoji
_PRIORITY_BADGE = {
    "critical": "🔴 Critical",
    "high": "🟠 High",
    "medium": "🟡 Medium",
    "low": "🟢 Low",
}


def _embed(
    title: str,
    description: str,
    color: int,
    project_id: str,
    fields: list[dict] | None = None,
) -> dict:
    """Build a base Discord embed dict with standard footer and timestamp."""
    embed: dict = {
        "title": title,
        "description": description,
        "color": color,
        "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
        "footer": {"text": f"Project: {project_id}"},
    }
    if fields:
        embed["fields"] = fields
    return embed


def _field(name: str, value: str, inline: bool = False) -> dict:
    return {"name": name, "value": value or "\u200b", "inline": inline}


# ---------------------------------------------------------------------------
# Task event formatters
# ---------------------------------------------------------------------------


def _task_created(project_id: str, data: dict) -> dict:
    title = data.get("title", "Untitled Task")
    priority = data.get("priority", "medium")
    task_id = data.get("task_id", "?")
    task_url = data.get("task_url", "")

    fields = [
        _field("Priority", _PRIORITY_BADGE.get(priority, priority), inline=True),
        _field("Task ID", f"#{task_id}", inline=True),
    ]
    assignee = data.get("assignee", "")
    if assignee:
        fields.append(_field("Assignee", assignee, inline=True))

    description = f"**[{title}]({task_url})**" if task_url else f"**{title}**"
    return _embed(
        title="Task Created",
        description=description,
        color=COLOR_GREEN,
        project_id=project_id,
        fields=fields,
    )


def _task_completed(project_id: str, data: dict) -> dict:
    title = data.get("title", "Untitled Task")
    task_id = data.get("id") or data.get("task_id", "?")
    lines_added = data.get("lines_added", 0)
    lines_deleted = data.get("lines_deleted", 0)
    duration = data.get("duration_seconds")
    work_log_summary = data.get("work_log_summary", "")
    work_log_test_result = data.get("work_log_test_result", "")

    fields = [
        _field("Task ID", f"#{task_id}", inline=True),
        _field("Lines", f"+{lines_added} / -{lines_deleted}", inline=True),
    ]
    if duration is not None:
        minutes, secs = divmod(int(duration), 60)
        fields.append(_field("Duration", f"{minutes}m {secs}s", inline=True))
    if work_log_test_result:
        fields.append(_field("Tests", work_log_test_result, inline=True))

    description = f"**{title}**"
    if work_log_summary:
        description += f"\n\n{work_log_summary[:1800]}"

    return _embed(
        title="Task Completed",
        description=description,
        color=COLOR_GOLD,
        project_id=project_id,
        fields=fields,
    )


def _task_failed(project_id: str, data: dict) -> dict:
    title = data.get("title", "Untitled Task")
    task_id = data.get("task_id", "?")
    error = data.get("error", "No error details provided.")

    fields = [
        _field("Task ID", f"#{task_id}", inline=True),
        _field("Error", f"```{error[:1000]}```", inline=False),
    ]
    return _embed(
        title="Task Failed",
        description=f"**{title}**",
        color=COLOR_RED,
        project_id=project_id,
        fields=fields,
    )


def _task_timeout(project_id: str, data: dict) -> dict:
    title = data.get("title", "Untitled Task")
    task_id = data.get("task_id", "?")
    timeout_secs = data.get("timeout_seconds")

    fields = [_field("Task ID", f"#{task_id}", inline=True)]
    if timeout_secs is not None:
        minutes, secs = divmod(int(timeout_secs), 60)
        fields.append(_field("Timeout After", f"{minutes}m {secs}s", inline=True))

    return _embed(
        title="Task Timed Out",
        description=f"**{title}**",
        color=COLOR_ORANGE,
        project_id=project_id,
        fields=fields,
    )


# ---------------------------------------------------------------------------
# Feature event formatters
# ---------------------------------------------------------------------------


def _feature_completed(project_id: str, data: dict) -> dict:
    name = data.get("name", "Untitled Feature")
    feature_id = data.get("feature_id", "?")
    task_count = data.get("task_count", 0)
    pr_url = data.get("pr_url", "")

    description = f"**{name}**"
    if pr_url:
        description += f"\n[View Pull Request]({pr_url})"

    fields = [
        _field("Feature ID", f"#{feature_id}", inline=True),
        _field("Tasks Completed", str(task_count), inline=True),
    ]
    return _embed(
        title="Feature Completed",
        description=description,
        color=COLOR_GOLD,
        project_id=project_id,
        fields=fields,
    )


# ---------------------------------------------------------------------------
# Lead capture formatter
# ---------------------------------------------------------------------------


def _lead_captured(project_id: str, data: dict) -> dict:
    name = data.get("name", "Unknown")
    email = data.get("email", "")
    gym = data.get("gym", "")

    fields = [
        _field("Email", email, inline=True),
    ]
    if gym:
        fields.append(_field("Gym / Box", gym, inline=True))

    return _embed(
        title="New Lead Captured",
        description=f"**{name}** submitted a lead via the website form.",
        color=COLOR_GREEN,
        project_id=project_id,
        fields=fields,
    )


# ---------------------------------------------------------------------------
# Public dispatch
# ---------------------------------------------------------------------------

_BUILDERS = {
    "task.created": _task_created,
    "task.completed": _task_completed,
    "task.failed": _task_failed,
    "task.timeout": _task_timeout,
    "feature.completed": _feature_completed,
    "lead.captured": _lead_captured,
}


def build_embed(event_type: str, project_id: str, data: dict) -> dict:
    """Return a Discord embed dict for the given event type and payload data.

    Args:
        event_type: The event type string (e.g. 'task.completed').
        project_id: The project that emitted the event — shown in the embed footer.
        data: Event-specific payload fields (varies by event type).

    Returns:
        A plain dict conforming to Discord's embed object schema.
        Suitable for use in the ``embeds`` array of a Discord message payload.
    """
    builder = _BUILDERS.get(event_type)
    if builder:
        return builder(project_id, data)
    return _embed(
        title=f"Event: {event_type}",
        description=str(data)[:2000],
        color=COLOR_GREEN,
        project_id=project_id,
    )
