from __future__ import annotations

from typing import Any


def resolve_published_batch(
    markers: list[dict[str, Any]],
    requested_date: str,
    legacy_date: str = "",
) -> tuple[dict[str, Any] | None, dict[str, Any], dict[str, Any] | None]:
    requested_marker = next(
        (
            item for item in markers
            if str(item.get("trade_date") or "") == requested_date
        ),
        None,
    )
    published = next(
        (item for item in markers if item.get("status") == "complete"),
        None,
    )
    if published is None and legacy_date:
        published = {
            "trade_date": legacy_date,
            "status": "complete",
            "legacy_inferred": True,
            "completed": [],
            "skipped": [],
            "failed": [],
        }

    request_status = dict(requested_marker or {})
    request_status.setdefault("trade_date", requested_date)
    request_status.setdefault("status", "pending")
    descriptor = _published_descriptor(published, requested_date, request_status)
    if descriptor and descriptor["is_fallback"]:
        request_status["retaining_trade_date"] = descriptor["trade_date"]
    return published, request_status, descriptor


def _published_descriptor(
    marker: dict[str, Any] | None,
    requested_date: str,
    request_status: dict[str, Any],
) -> dict[str, Any] | None:
    if marker is None:
        return None
    trade_date = str(marker.get("trade_date") or "")
    is_fallback = trade_date != requested_date
    status = str(request_status.get("status") or "pending")
    notice = ""
    if is_fallback:
        if status == "running":
            notice = "所选日期候选正在生成，当前保留上一成功批次"
        elif status in {"failed", "partial"}:
            notice = "所选日期候选未完整发布，当前保留上一成功批次"
        else:
            notice = "所选日期候选尚未发布，当前展示最近成功批次"
    return {
        "trade_date": trade_date,
        "status": "complete",
        "started_at": marker.get("started_at") or "",
        "finished_at": marker.get("finished_at") or marker.get("updated_at") or "",
        "library_version": int(marker.get("library_version") or 0),
        "completed_count": len(marker.get("completed") or []),
        "skipped_count": len(marker.get("skipped") or []),
        "legacy_inferred": bool(marker.get("legacy_inferred")),
        "is_fallback": is_fallback,
        "notice": notice,
    }
