"""Review feedback service."""

from __future__ import annotations

from sqlalchemy.orm import Session

from fenliu.models import Post
from fenliu.models import ReviewFeedback
from fenliu.utils.html import strip_html_tags


def create_review_feedback(
    post: Post,
    decision: str,
    db: Session,
    *,
    manual_score: int | None = None,
    reviewer_notes: str | None = None,
) -> ReviewFeedback:
    """Build and persist a ReviewFeedback snapshot from a Post at review time.

    Adds the record to the session; the caller is responsible for committing.
    """
    attachments: list[dict] = post.media_attachments if isinstance(post.media_attachments, list) else []
    has_video = any(a.get("type") == "video" for a in attachments)
    feedback = ReviewFeedback(
        post_id=post.id,
        decision=decision,
        manual_score=manual_score,
        reviewer_notes=reviewer_notes or None,
        content_snippet=strip_html_tags(post.content or "")[:500] if post.content else None,
        spam_score_at_review=post.spam_score,
        hashtag_count=len(post.hashtags) if post.hashtags else 0,
        hashtags_snapshot=post.hashtags,
        attachment_count=len(attachments),
        has_video=has_video,
        boosts=post.boosts,
        likes=post.likes,
        replies=post.replies,
        author_is_bot=post.author_is_bot,
        instance=post.instance,
        stream_id=post.stream_id,
    )
    db.add(feedback)
    return feedback
