from __future__ import annotations

import json
from datetime import datetime

from mrp.models import Message

from mrp_mcp.state import SessionState


def format_message(msg: Message, state: SessionState, own_key: str | None = None) -> str:
    """Format a single message for display."""
    sender = state.contacts.get(msg.sender_key)
    if own_key and msg.sender_key == own_key:
        name = "You"
    elif sender and sender.display_name:
        name = sender.display_name
    else:
        name = msg.sender_key[:12] + "..."

    lines = []
    lines.append(f"**From:** {name}")
    lines.append(f"**Message ID:** {msg.message_id}")
    if msg.thread_id:
        lines.append(f"**Thread:** {msg.thread_id}")
    lines.append(f"**Time:** {msg.created_at.isoformat()}")
    lines.append("**Content:**")
    if isinstance(msg.body, dict) and "text" in msg.body:
        lines.append(msg.body["text"])
    else:
        lines.append(f"```json\n{json.dumps(msg.body, indent=2)}\n```")
    if msg.attachments:
        lines.append(f"**Attachments:** {len(msg.attachments)} file(s)")
        for att in msg.attachments:
            size = f", {att.size} bytes" if att.size else ""
            ct = f" ({att.content_type}{size})" if att.content_type else ""
            lines.append(f"  - {att.blob_id}{ct}")
    return "\n".join(lines)


def format_thread_message(msg: Message, state: SessionState, own_key: str) -> str:
    """Format a message within a thread view."""
    sender = state.contacts.get(msg.sender_key)
    if msg.sender_key == own_key:
        label = "You"
    elif sender and sender.display_name:
        label = sender.display_name
    else:
        label = msg.sender_key[:12] + "..."

    time_str = msg.created_at.strftime("%H:%M:%S")
    lines = [f"**[{label}]** ({time_str})"]
    if isinstance(msg.body, dict) and "text" in msg.body:
        lines.append(f"  {msg.body['text']}")
    else:
        lines.append(f"  ```json\n  {json.dumps(msg.body, indent=2)}\n  ```")
    return "\n".join(lines)


def format_contact_name(state: SessionState, public_key: str) -> str:
    """Get a display name for a public key."""
    contact = state.contacts.get(public_key)
    if contact and contact.display_name:
        return contact.display_name
    return public_key[:12] + "..."
