"""Tests for MRP MCP server formatting utilities."""

from __future__ import annotations

from datetime import datetime, timezone

import pytest

from mrp.models import Attachment, DiscoveredAgent, Message
from mrp_mcp.formatting import format_contact_name, format_message, format_thread_message
from mrp_mcp.state import SessionState


def _now():
    return datetime.now(timezone.utc)


def _make_message(
    sender_key="sender-pk-abcdefghijklmnopqrstuvwxyz1234",
    body=None,
    thread_id=None,
    attachments=None,
    message_id="msg_100",
):
    return Message(
        message_id=message_id,
        sender_key=sender_key,
        recipient_key="test-pk-1234567890abcdefghijklmnopqrstuv",
        content_type="application/json",
        body=body if body is not None else {"text": "Hello there!"},
        attachments=attachments or [],
        status="sent",
        thread_id=thread_id,
        in_reply_to=None,
        metadata={},
        created_at=_now(),
        expires_at=_now(),
    )


def _state_with_contact(pk="sender-pk-abcdefghijklmnopqrstuvwxyz1234", name="Alice"):
    state = SessionState()
    state.add_contact(
        DiscoveredAgent(
            public_key=pk,
            display_name=name,
            last_active_at=_now(),
            capabilities=["text:chat"],
        )
    )
    return state


class TestFormatMessage:
    def test_format_message_known_contact(self, state):
        state.add_contact(
            DiscoveredAgent(
                public_key="sender-pk-abcdefghijklmnopqrstuvwxyz1234",
                display_name="Alice",
                last_active_at=_now(),
                capabilities=[],
            )
        )
        msg = _make_message()
        result = format_message(msg, state)
        assert "**From:** Alice" in result

    def test_format_message_unknown_contact(self, state):
        msg = _make_message(sender_key="unknown-pk-abcdefghijklmnopqrstuvwxyz")
        result = format_message(msg, state)
        assert "**From:** unknown-pk-a..." in result

    def test_format_message_from_self(self, state):
        own_key = "my-pk-abcdefghijklmnopqrstuvwxyz12345"
        msg = _make_message(sender_key=own_key)
        result = format_message(msg, state, own_key=own_key)
        assert "**From:** You" in result

    def test_format_message_text_body(self, state):
        msg = _make_message(body={"text": "Hello world"})
        result = format_message(msg, state)
        assert "Hello world" in result
        assert "```json" not in result

    def test_format_message_json_body(self, state):
        msg = _make_message(body={"action": "ping", "data": 42})
        result = format_message(msg, state)
        assert "```json" in result
        assert '"action"' in result
        assert '"ping"' in result

    def test_format_message_with_thread(self, state):
        msg = _make_message(thread_id="thread-abc")
        result = format_message(msg, state)
        assert "**Thread:** thread-abc" in result

    def test_format_message_with_attachments(self, state):
        atts = [
            Attachment(blob_id="blob_001", content_type="image/png", size=2048),
            Attachment(blob_id="blob_002", content_type="text/plain", size=None),
        ]
        msg = _make_message(attachments=atts)
        result = format_message(msg, state)
        assert "**Attachments:** 2 file(s)" in result
        assert "blob_001" in result
        assert "image/png" in result
        assert "2048 bytes" in result
        assert "blob_002" in result

    def test_format_message_no_attachments(self, state):
        msg = _make_message(attachments=[])
        result = format_message(msg, state)
        assert "Attachments" not in result

    def test_format_message_contains_message_id(self, state):
        msg = _make_message(message_id="msg_xyz")
        result = format_message(msg, state)
        assert "**Message ID:** msg_xyz" in result

    def test_format_message_contains_time(self, state):
        msg = _make_message()
        result = format_message(msg, state)
        assert "**Time:**" in result


class TestFormatThreadMessage:
    def test_format_thread_message_self(self, state):
        own_key = "my-pk-abcdefghijklmnopqrstuvwxyz12345"
        msg = _make_message(sender_key=own_key, body={"text": "My reply"})
        result = format_thread_message(msg, state, own_key)
        assert "**[You]**" in result
        assert "My reply" in result

    def test_format_thread_message_contact(self, state):
        state.add_contact(
            DiscoveredAgent(
                public_key="sender-pk-abcdefghijklmnopqrstuvwxyz1234",
                display_name="Bob",
                last_active_at=_now(),
                capabilities=[],
            )
        )
        msg = _make_message(body={"text": "Hi from Bob"})
        result = format_thread_message(msg, state, "my-pk")
        assert "**[Bob]**" in result
        assert "Hi from Bob" in result

    def test_format_thread_message_unknown(self, state):
        msg = _make_message(
            sender_key="unknown-pk-abcdefghijklmnopqrstuvwxyz",
            body={"text": "Mystery"},
        )
        result = format_thread_message(msg, state, "my-pk")
        assert "**[unknown-pk-a...]**" in result

    def test_format_thread_message_indent(self, state):
        msg = _make_message(body={"text": "Indented text"})
        result = format_thread_message(msg, state, "my-pk")
        # Text body lines should be indented with two spaces
        assert "  Indented text" in result

    def test_format_thread_message_json_body(self, state):
        msg = _make_message(body={"action": "update"})
        result = format_thread_message(msg, state, "my-pk")
        assert "```json" in result


class TestFormatContactName:
    def test_format_contact_name_known(self, state):
        state.add_contact(
            DiscoveredAgent(
                public_key="pk-known-abcdefghijklmnopqrstuvwxy",
                display_name="Charlie",
                last_active_at=_now(),
                capabilities=[],
            )
        )
        result = format_contact_name(state, "pk-known-abcdefghijklmnopqrstuvwxy")
        assert result == "Charlie"

    def test_format_contact_name_no_name(self, state):
        state.add_contact(
            DiscoveredAgent(
                public_key="pk-noname-abcdefghijklmnopqrstuvw",
                display_name=None,
                last_active_at=_now(),
                capabilities=[],
            )
        )
        result = format_contact_name(state, "pk-noname-abcdefghijklmnopqrstuvw")
        assert result == "pk-noname-ab..."

    def test_format_contact_name_unknown(self, state):
        result = format_contact_name(state, "pk-unknown-abcdefghijklmnopqrstu")
        assert result == "pk-unknown-a..."
