"""
Formatting and helper utilities for CodeContext server.
"""

import json
from datetime import datetime as dt
from fastapi.responses import JSONResponse


def error_response(detail: str, code: str = None, status_code: int = 400):
    """Create standardized error response."""
    content = {"status": "error", "detail": detail}
    if code:
        content["code"] = code
    return JSONResponse(content=content, status_code=status_code)


def format_datetime(iso_string: str) -> str:
    """Format ISO datetime to 'Jan 17, 2026 · 3:45 PM'."""
    if not iso_string:
        return ""
    try:
        parsed = dt.fromisoformat(iso_string.replace("Z", "+00:00"))
        return parsed.strftime("%b %d, %Y · %I:%M %p")
    except (ValueError, AttributeError):
        return iso_string[:10] if len(iso_string) >= 10 else iso_string


def format_memories_datetime(memories: list) -> list:
    """Format created_at for a list of memories."""
    for m in memories:
        if "created_at" in m and m["created_at"]:
            m["formatted_date"] = format_datetime(m["created_at"])
    return memories


def sse_event(data: dict, event: str = None) -> str:
    """Format data as Server-Sent Event."""
    lines = []
    if event:
        lines.append(f"event: {event}")
    lines.append(f"data: {json.dumps(data)}")
    lines.append("")  # Empty line to end the event
    return "\n".join(lines) + "\n"
