"""Media stabilization service for the formal acquisition pipeline."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Callable

from acquisition.media.oss_client import to_oss
from core.config import Settings


@dataclass(frozen=True)
class StabilizedMedia:
    media_type: str
    source_url: str
    cdn_url: str
    position: int
    status: str = "ready"


Uploader = Callable[[str, str], str]


def stabilize_media_urls(
    *,
    image_urls: list[str] | None = None,
    video_urls: list[str] | None = None,
    settings: Settings | None = None,
    uploader: Uploader | None = None,
) -> list[StabilizedMedia]:
    """Transfer image/video URLs to OSS/CDN and return DB-ready media rows.

    The uploader falls back to the original source URL when OSS transfer fails,
    so acquisition can still store the candidate and make the failure visible in
    later review instead of dropping the item.
    """
    upload = uploader or (
        lambda url, media_type: to_oss(url, media_type, settings=settings)
    )
    rows: list[StabilizedMedia] = []
    position = 0
    for url in image_urls or []:
        if not url:
            continue
        position += 1
        try:
            cdn = upload(url, "image")
        except Exception:
            cdn = url
        rows.append(
            StabilizedMedia(
                media_type="image",
                source_url=url,
                cdn_url=cdn,
                position=position,
                status="ready" if cdn else "failed",
            )
        )
    for url in video_urls or []:
        if not url:
            continue
        position += 1
        try:
            cdn = upload(url, "video")
        except Exception:
            cdn = url
        rows.append(
            StabilizedMedia(
                media_type="video",
                source_url=url,
                cdn_url=cdn,
                position=position,
                status="ready" if cdn else "failed",
            )
        )
    return rows
