from flask import Blueprint, make_response, redirect, render_template, url_for

from src.config import Configuration
from src.lib.post import get_post_revisions
from src.pages.post import ready_post_props

revisions_bp = Blueprint("revisions", __name__)


@revisions_bp.route("/<service>/user/<artist_id>/post/<post_id>/revision/<revision_id>")
def get(service: str, artist_id: str, post_id: str, revision_id: str):
    revisions = get_post_revisions(service, artist_id, post_id) if revision_id.isdigit() else []
    revision = next((rev for rev in revisions if rev["revision_id"] == int(revision_id)), None)
    if not revision or not (
        service == revision["service"] and artist_id == revision["user"] and post_id == revision["id"]
    ):
        response = redirect(url_for("post.get", service=service, artist_id=artist_id, post_id=get))
        return response

    attachments, comments, previews, videos, props = ready_post_props(revision)
    props["currentPage"] = "revisions"

    response = make_response(
        render_template(
            "post.html",
            props=props,
            post=revision,
            comments=comments,
            result_previews=previews,
            result_attachments=attachments,
            videos=videos,
            archives_enabled=Configuration().archive_server["enabled"],
        ),
        200,
    )
    response.headers["Cache-Control"] = "s-maxage=600"
    return response
