"""master 节点专用：计算实时行情后上传到 S3"""

from pathlib import Path

from minio import Minio

from ldnode import logger
from ldnode.loader.schemas.enumerations import SyncStatus
from ldnode.loader.schemas.models import DataSource, SyncResult


class QuotationComputeAndUploadDataSource(DataSource):
    """装饰器数据源：先调用内部数据源计算行情，成功后上传到 S3"""

    def __init__(self, compute_source: DataSource, s3_client: Minio, bucket: str, local_data_dir: Path):
        self._compute = compute_source
        self._client = s3_client
        self._bucket = bucket
        self._local_dir = local_data_dir

    def load(self, key: str) -> list[SyncResult]:
        results = self._compute.load(key)
        if any(r.status == SyncStatus.SUCCESS for r in results):
            local_path = self._local_dir / key
            if local_path.exists():
                try:
                    self._client.fput_object(self._bucket, key, str(local_path))
                    logger.loader.info(f"[Quotation] 行情已上传 S3: {key}")
                except Exception as e:
                    logger.loader.warning(f"[Quotation] 行情上传 S3 失败 ({key}): {e}")
        return results
