"""
MinIO 存储连接管理
"""
import os
import logging
import uuid
import io
from datetime import datetime, timedelta
from typing import Optional, Tuple, Dict, Any
from minio import Minio

# 导入配置
from app.core.config import config_handler

logger = logging.getLogger(__name__)

_minio_manager = None

class MinioManager:
    """MinIO 管理器"""
    
    def __init__(self):
        self.endpoint = config_handler.get("admin_app", "MINIO_ENDPOINT", "192.168.91.15:19000")
        self.access_key = config_handler.get("admin_app", "MINIO_ACCESS_KEY", "minioadmin")
        self.secret_key = config_handler.get("admin_app", "MINIO_SECRET_KEY", "minioadmin")
        self.bucket_name = config_handler.get("admin_app", "MINIO_BUCKET_NAME", "lq-bucket")
        self.secure = config_handler.get_bool("admin_app", "MINIO_USE_SSL", False)
        self.base_path = config_handler.get("admin_app", "MINIO_BASE_PATH", "lqadmin")
        
        self._client = None
        logger.info(f"初始化 MinIO 管理器: endpoint={self.endpoint}, bucket={self.bucket_name}")

    @property
    def client(self) -> Minio:
        """获取 MinIO 客户端（延迟初始化）"""
        if self._client is None:
            try:
                self._client = Minio(
                    self.endpoint,
                    access_key=self.access_key,
                    secret_key=self.secret_key,
                    secure=self.secure
                )
                # 确保桶存在
                if not self._client.bucket_exists(self.bucket_name):
                    self._client.make_bucket(self.bucket_name)
                logger.info("MinIO 客户端初始化成功")
            except Exception as e:
                logger.error(f"MinIO 客户端初始化失败: {e}")
                raise
        return self._client

    def get_upload_url(self, filename: str, content_type: str, expires_minutes: int = 15) -> Dict[str, Any]:
        """生成预签名上传 URL"""
        unique_id = str(uuid.uuid4())
        ext = os.path.splitext(filename)[1]
        object_name = f"{self.base_path}/uploads/{datetime.now().strftime('%Y%m%d')}/{unique_id}{ext}"
        
        # 生成预签名 URL (PUT)
        upload_url = self.client.presigned_put_object(
            self.bucket_name,
            object_name,
            expires=timedelta(minutes=expires_minutes)
        )
        
        # 构造访问 URL
        file_url = f"http://{self.endpoint}/{self.bucket_name}/{object_name}"
        
        return {
            "upload_url": upload_url,
            "file_url": file_url,
            "object_name": object_name
        }

    def upload_file(self, file_content: bytes, object_name: str, content_type: str = "application/octet-stream") -> str:
        """上传文件内容到 MinIO"""
        self.client.put_object(
            self.bucket_name,
            object_name,
            io.BytesIO(file_content),
            len(file_content),
            content_type=content_type
        )
        return f"http://{self.endpoint}/{self.bucket_name}/{object_name}"

def get_minio_manager() -> MinioManager:
    """获取 MinIO 管理器单例"""
    global _minio_manager
    if _minio_manager is None:
        _minio_manager = MinioManager()
    return _minio_manager

def init_minio():
    """初始化 MinIO"""
    return get_minio_manager()
