"""S3 行情读取数据源（slave 节点从 S3 读取 master 上传的行情）"""

import os
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 S3QuotationDataSource(DataSource):
    """从 S3 读取实时行情文件（slave 节点使用）"""

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

    def load(self, key: str) -> list[SyncResult]:
        local_path = self._local_dir / key
        try:
            resp = self._client.get_object(self._bucket, key)
            try:
                data = resp.read()
            finally:
                resp.close()
                resp.release_conn()
            local_path.parent.mkdir(parents=True, exist_ok=True)
            tmp_path = local_path.with_suffix(".tmp")
            tmp_path.write_bytes(data)
            os.rename(tmp_path, local_path)
            logger.loader.debug(f"[Quotation] S3 行情已同步: {key} size={len(data)}")
            return [SyncResult(key, SyncStatus.SUCCESS, f"size={len(data)}")]
        except Exception as e:
            logger.loader.warning(f"[Quotation] S3 行情同步失败 ({key}): {e}")
            return [SyncResult(key, SyncStatus.FAILED, str(e))]
