from __future__ import annotations

import logging
from typing import Any

from backend.services.artifact_models import ArtifactReference, PreparedToolSourceArtifact
from backend.services.artifact_read_service.service import resolve_artifact_read_for_llm_payload

logger = logging.getLogger(__name__)


def prepare_source_artifacts_for_tool(
    *,
    source_artifacts: list[ArtifactReference],
    context: dict[str, Any] | None,
    app,
    accepted_read_modes: set[str],
) -> list[PreparedToolSourceArtifact]:
    """Prepare persisted conversation artifacts so another tool can consume them as backend-owned source input.

    The orchestrator passes explicit artifact references, not raw artifact payloads. This helper resolves each
    reference through the shared artifact-read service, keeps only successfully prepared artifacts whose read mode
    is accepted by the caller tool, and returns a compact typed payload ready for prompt assembly or other
    tool-specific consumption.

    In the current PPTX flow, this is the bridge between `generate_pptx(source_artifacts=[...])` and the generic
    artifact-reading stack: the tool asks for records from conversation history, this helper reloads them from
    storage, reuses the canonical LLM-readable normalization, and filters out unsupported or failed reads.
    """
    if not source_artifacts:
        return []

    prepared: list[PreparedToolSourceArtifact] = []
    for reference in source_artifacts:
        resolved = resolve_artifact_read_for_llm_payload(
            message_id=reference.message_id,
            artifacts_id=reference.artifacts_id,
            artifact_index=reference.artifact_index,
            context=context,
            app=app,
        )
        read_result = resolved.read_result
        # Keep `partial` because an artifact can still be useful, for example if 2 images were found and only 1 could be attached to the LLM.
        if read_result.status not in {"ok", "partial"}:
            logger.warning(
                "Source artifact resolution failed for tool input: status=%s read_mode=%s reference=%s/%s/%s",
                read_result.status or "unknown",
                read_result.read_mode or "unknown",
                reference.message_id,
                reference.artifacts_id,
                reference.artifact_index,
            )
            continue
        if read_result.read_mode not in accepted_read_modes:
            logger.info(
                "Skipping source artifact for unsupported read mode: read_mode=%s reference=%s/%s/%s",
                read_result.read_mode or "unknown",
                reference.message_id,
                reference.artifacts_id,
                reference.artifact_index,
            )
            continue
        prepared.append(
            PreparedToolSourceArtifact(
                reference=reference,
                artifact_name=read_result.artifact_name,
                read_mode=read_result.read_mode,
                content=read_result.content_text,
                parts=read_result.parts,
            )
        )
    return prepared
