"""
OSS 上传任务数据库模型
"""
from datetime import datetime
from sqlalchemy import Column, String, Integer, DateTime, BigInteger, Text

from database import Base, engine


class OSSUploadTask(Base):
    """OSS 上传任务"""
    __tablename__ = "oss_upload_tasks"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)

    # 用户信息
    user_id = Column(String(64), index=True, nullable=False)
    user_name = Column(String(128), nullable=False)
    token_hash = Column(String(64), nullable=False)

    # 文件信息
    dataset_id = Column(String(128), index=True, nullable=False)
    file_name = Column(String(512), nullable=False)
    file_size = Column(BigInteger, nullable=True, comment="最终文件大小")
    file_path = Column(String(1024), nullable=True, comment="OSS 最终路径")
    oss_key = Column(String(1024), nullable=False, comment="OSS 对象 key")

    # 状态: pending / uploading_to_oss / transferring / completed / failed
    status = Column(String(32), nullable=False, default="pending", index=True)
    error_message = Column(Text, nullable=True)

    # 时间
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
    transfer_started_at = Column(DateTime, nullable=True)
    completed_at = Column(DateTime, nullable=True)

    def to_dict(self) -> dict:
        return {
            "task_id": self.id,
            "dataset_id": self.dataset_id,
            "file_name": self.file_name,
            "file_size": self.file_size,
            "file_path": self.file_path,
            "oss_key": self.oss_key,
            "status": self.status,
            "error_message": self.error_message,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "transfer_started_at": self.transfer_started_at.isoformat() if self.transfer_started_at else None,
            "completed_at": self.completed_at.isoformat() if self.completed_at else None,
        }


def create_oss_tables():
    """创建 OSS 相关表"""
    Base.metadata.create_all(bind=engine)
