"""
数据库配置和模型
"""
import os
from datetime import datetime
from typing import Optional, List
from sqlalchemy import create_engine, Column, String, Integer, DateTime, Text, Boolean, BigInteger
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.dialects.mysql import LONGTEXT
import json

# MySQL数据库配置
MYSQL_HOST = os.getenv("MYSQL_HOST", "localhost")
MYSQL_PORT = os.getenv("MYSQL_PORT", "3306")
MYSQL_USER = os.getenv("MYSQL_USER", "root")
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "")
MYSQL_DATABASE = os.getenv("MYSQL_DATABASE", "file_upload_db")

DATABASE_URL = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}?charset=utf8mb4"

engine = create_engine(
    DATABASE_URL,
    echo=False,  # 设为True可以看到SQL日志
    pool_pre_ping=True,  # 自动重连
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


class TokenRecord(Base):
    """Token数据库模型（简化版）"""
    __tablename__ = "tokens"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    
    # Token信息
    token_hash = Column(String(64), unique=True, index=True, nullable=False)
    
    # 用户信息
    user_id = Column(String(64), index=True, nullable=False)
    user_name = Column(String(128), nullable=False)
    role = Column(String(16), nullable=False, default="user")
    
    # 权限配置
    # 1TB 默认
    max_file_size = Column(BigInteger, nullable=False, default=1024 * 1024 * 1024 * 1024)
    daily_upload_limit = Column(Integer, nullable=False, default=100)
    
    # 时间信息
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
    last_used_at = Column(DateTime, nullable=True)
    
    # 使用统计
    usage_count = Column(Integer, nullable=False, default=0)
    daily_usage = Column(Integer, nullable=False, default=0)
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "id": self.id,
            "token_hash": self.token_hash,
            "user_id": self.user_id,
            "user_name": self.user_name,
            "role": self.role,
            "max_file_size": self.max_file_size,
            "daily_upload_limit": self.daily_upload_limit,
            "created_at": self.created_at,
            "last_used_at": self.last_used_at,
            "usage_count": self.usage_count,
            "daily_usage": self.daily_usage
        }


class FileUploadRecord(Base):
    """文件上传记录数据库模型"""
    __tablename__ = "file_upload_records"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    
    # 用户信息
    user_id = Column(String(64), index=True, nullable=False, comment="用户ID")
    user_name = Column(String(128), nullable=False, comment="用户名")
    token_hash = Column(String(64), index=True, nullable=False, comment="使用的Token Hash")
    
    # 文件信息
    file_id = Column(String(128), unique=True, index=True, nullable=False, comment="文件唯一标识符")
    file_name = Column(String(512), nullable=False, comment="文件名")
    file_size = Column(BigInteger, nullable=False, comment="文件大小(字节)")
    file_md5 = Column(String(32), nullable=True, comment="文件MD5值")
    
    # 存储信息
    file_path = Column(String(1024), nullable=False, comment="文件存储路径")
    dataset_id = Column(String(128), index=True, nullable=False, comment="数据集ID")
    
    # 上传信息
    total_chunks = Column(Integer, nullable=False, comment="分片总数")
    upload_status = Column(String(16), nullable=False, default="completed", comment="上传状态")
    
    # 时间信息
    upload_started_at = Column(DateTime, nullable=True, comment="上传开始时间")
    upload_completed_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="上传完成时间")
    created_at = Column(DateTime, nullable=False, default=datetime.utcnow, index=True, comment="记录创建时间")
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "user_name": self.user_name,
            "token_hash": self.token_hash,
            "file_id": self.file_id,
            "file_name": self.file_name,
            "file_size": self.file_size,
            "file_md5": self.file_md5,
            "file_path": self.file_path,
            "dataset_id": self.dataset_id,
            "total_chunks": self.total_chunks,
            "upload_status": self.upload_status,
            "upload_started_at": self.upload_started_at.isoformat() if self.upload_started_at else None,
            "upload_completed_at": self.upload_completed_at.isoformat() if self.upload_completed_at else None,
            "created_at": self.created_at.isoformat() if self.created_at else None
        }


def create_tables():
    """创建所有表"""
    Base.metadata.create_all(bind=engine)
    print("✅ 数据库表创建完成")


def get_database_session() -> Session:
    """获取数据库会话"""
    db = SessionLocal()
    try:
        return db
    except Exception as e:
        db.close()
        raise e


# 数据库依赖注入
def get_db():
    """FastAPI依赖注入：获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def init_database():
    """初始化数据库"""
    try:
        create_tables()
        print(f"✅ 数据库初始化完成: {DATABASE_URL}")
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")
        raise


if __name__ == "__main__":
    # 直接运行此文件可以初始化数据库
    init_database()
