"""Network conversation logger.

Logs all ALP network activity to ~/.alive/network/conversations.log in a
human-readable format. This is the viral demo — it needs to look good.
"""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path


def _log_path() -> Path:
    from alive.config import ALIVE_HOME

    return ALIVE_HOME / "network" / "conversations.log"


def log_event(event_type: str, detail: str) -> None:
    """Append a timestamped event to the conversation log.

    Args:
        event_type: Category like ANNOUNCE, DISCOVERED, SENT, RECEIVED, etc.
        detail: Human-readable description of what happened.
    """
    path = _log_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] {event_type} \u2192 {detail}\n"
    with open(path, "a") as f:
        f.write(line)


def read_log(lines: int = 50) -> list[str]:
    """Read the most recent log entries.

    Args:
        lines: Maximum number of lines to return.

    Returns:
        List of log lines (most recent last).
    """
    path = _log_path()
    if not path.exists():
        return []
    all_lines = path.read_text().splitlines()
    return all_lines[-lines:]


def clear_log() -> None:
    """Clear the conversation log."""
    path = _log_path()
    if path.exists():
        path.write_text("")
