"""复盘截图即时上传 API(三所共用)."""
from __future__ import annotations

from typing import Any, Callable, Dict, Tuple

from lib.instance.journal_images_lib import (
    JOURNAL_UPLOAD_TFS,
    normalize_journal_draft_id,
    save_journal_slot_file,
)


def handle_journal_upload_slot(
    request: Any,
    *,
    upload_folder: str,
    secure_filename_fn: Callable[[str], str],
) -> Tuple[Dict[str, Any], int]:
    """POST multipart: journal_draft_id, tf, file → {ok, file}."""
    draft_id = normalize_journal_draft_id(
        request.form.get("journal_draft_id") if request.form else None
    )
    tf = str((request.form.get("tf") if request.form else None) or "").strip()
    if not draft_id:
        return {"ok": False, "error": "invalid draft_id"}, 400
    if tf not in JOURNAL_UPLOAD_TFS:
        return {"ok": False, "error": "invalid tf"}, 400

    f = request.files.get("file") if request.files else None
    if not f or not getattr(f, "filename", None):
        return {"ok": False, "error": "no file"}, 400

    item = save_journal_slot_file(
        f,
        draft_id,
        tf,
        upload_folder,
        secure_filename_fn=secure_filename_fn,
    )
    if not item:
        return {"ok": False, "error": "save failed"}, 500

    return {"ok": True, "tf": tf, "file": item["file"]}, 200
