"""Display helpers: convert ORM objects to template-ready dicts."""

from __future__ import annotations

import json
from datetime import UTC
from datetime import datetime
from typing import Any

from fenliu.logging import get_logger
from fenliu.models import HashtagStream
from fenliu.models import Post

logger = get_logger(__name__)


def make_datetime_aware(dt: datetime | None) -> datetime | None:
    """Convert naive datetime to timezone-aware UTC datetime."""
    logger.debug(f"make_datetime_aware: input={dt}, tzinfo={dt.tzinfo if dt else None}")
    if dt is not None and dt.tzinfo is None:
        result = dt.replace(tzinfo=UTC)
        logger.debug(f"make_datetime_aware: converted to {result}")
        return result
    return dt


def process_post_for_display(post: Post) -> dict[str, Any]:
    """Convert post object to display-ready dictionary with timezone-aware datetimes."""
    logger.debug(f"process_post_for_display: post_id={post.id}, url={post.url}")
    post_dict = {c.name: getattr(post, c.name) for c in post.__table__.columns}
    post_dict["created_at"] = make_datetime_aware(post.created_at)
    post_dict["fetched_at"] = make_datetime_aware(post.fetched_at)
    # Ensure media_attachments is properly serialized (it's JSON in database)
    if post_dict.get("media_attachments") and isinstance(post_dict["media_attachments"], str):
        try:
            post_dict["media_attachments"] = json.loads(post_dict["media_attachments"])
            logger.debug(f"process_post_for_display: parsed media_attachments for post {post.id}")
        except (json.JSONDecodeError, TypeError) as e:
            logger.debug(f"process_post_for_display: failed to parse media_attachments: {e}")
            post_dict["media_attachments"] = []
    # Include stream information if available
    if post.stream:
        logger.debug(f"process_post_for_display: processing stream {post.stream.hashtag}")
        post_dict["stream"] = process_stream_for_display(post.stream)
    return post_dict


def process_stream_for_display(stream: HashtagStream) -> dict[str, Any]:
    """Convert stream object to display-ready dictionary with timezone-aware datetimes."""
    logger.debug(f"process_stream_for_display: hashtag={stream.hashtag}, instance={stream.instance}")
    stream_dict = {c.name: getattr(stream, c.name) for c in stream.__table__.columns}
    stream_dict["last_check"] = make_datetime_aware(stream.last_check)
    stream_dict["created_at"] = make_datetime_aware(stream.created_at)
    stream_dict["updated_at"] = make_datetime_aware(stream.updated_at)
    stream_dict["next_scheduled_fetch"] = make_datetime_aware(stream.next_scheduled_fetch)
    return stream_dict
