from sqlalchemy import Column, Integer, String, Float, Text, Boolean, DateTime, ForeignKey, JSON
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

from app.models.database import Base


class Algorithm(Base):
    """算法模型"""
    __tablename__ = "algorithms"
    
    id = Column(String, primary_key=True, index=True)
    name = Column(String, nullable=False, index=True)
    description = Column(Text, nullable=False)
    type = Column(String, nullable=False, index=True)  # computer_vision, nlp, ml, edge_computing, medical, autonomous_driving等
    status = Column(String, default="active", index=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    versions = relationship("AlgorithmVersion", back_populates="algorithm", cascade="all, delete-orphan")
    calls = relationship("AlgorithmCall", back_populates="algorithm")


class AlgorithmVersion(Base):
    """算法版本模型"""
    __tablename__ = "algorithm_versions"
    
    id = Column(String, primary_key=True, index=True)
    algorithm_id = Column(String, ForeignKey("algorithms.id"), nullable=False, index=True)
    version = Column(String, nullable=False)
    url = Column(String, nullable=False)  # 算法API地址
    params = Column(JSON, default=dict)  # 算法参数配置
    input_schema = Column(JSON, default=dict)  # 输入数据格式
    output_schema = Column(JSON, default=dict)  # 输出数据格式
    code = Column(Text, default='')  # Python算法代码
    model_name = Column(String, default='')  # API训练后的模型名字
    model_file = Column(String, default='')  # 模型文件路径
    api_doc = Column(Text, default='')  # 模型的API用法文档
    is_default = Column(Boolean, default=False)  # 是否为默认版本
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    algorithm = relationship("Algorithm", back_populates="versions")
    calls = relationship("AlgorithmCall", back_populates="version")


class User(Base):
    """用户模型"""
    __tablename__ = "users"
    
    id = Column(String, primary_key=True, index=True)
    username = Column(String, unique=True, nullable=False, index=True)
    email = Column(String, unique=True, nullable=False, index=True)
    password_hash = Column(String, nullable=False)
    role = Column(String, default="user", index=True)  # admin, user, customer
    status = Column(String, default="active", index=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    api_keys = relationship("APIKey", back_populates="user", cascade="all, delete-orphan")
    calls = relationship("AlgorithmCall", back_populates="user")


class APIKey(Base):
    """API密钥模型"""
    __tablename__ = "api_keys"
    
    id = Column(String, primary_key=True, index=True)
    user_id = Column(String, ForeignKey("users.id"), nullable=False, index=True)
    key = Column(String, unique=True, nullable=False, index=True)
    name = Column(String, nullable=False)
    expires_at = Column(DateTime(timezone=True), nullable=False)
    status = Column(String, default="active", index=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    user = relationship("User", back_populates="api_keys")


class AlgorithmCall(Base):
    """算法调用记录模型"""
    __tablename__ = "algorithm_calls"
    
    id = Column(String, primary_key=True, index=True)
    user_id = Column(String, ForeignKey("users.id"), nullable=False, index=True)
    algorithm_id = Column(String, ForeignKey("algorithms.id"), nullable=False, index=True)
    version_id = Column(String, ForeignKey("algorithm_versions.id"), nullable=False, index=True)
    input_data = Column(JSON, nullable=False)  # 输入数据
    params = Column(JSON, default=dict)  # 调用参数
    output_data = Column(JSON, default=dict)  # 输出数据
    status = Column(String, default="pending", index=True)  # pending, running, success, failed
    response_time = Column(Float, nullable=True)  # 响应时间（秒）
    error_message = Column(Text, nullable=True)  # 错误信息
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    user = relationship("User", back_populates="calls")
    algorithm = relationship("Algorithm", back_populates="calls")
    version = relationship("AlgorithmVersion", back_populates="calls")


class GiteaConfig(Base):
    """Gitea配置模型"""
    __tablename__ = "gitea_configs"
    
    id = Column(String, primary_key=True, index=True)
    server_url = Column(String, nullable=False)  # Gitea服务器URL
    access_token = Column(String, nullable=False)  # 访问令牌
    default_owner = Column(String, nullable=False)  # 默认组织/用户
    repo_prefix = Column(String, default="")  # 仓库前缀
    status = Column(String, default="active")  # 状态
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())


class AlgorithmRepository(Base):
    """算法仓库模型"""
    __tablename__ = "algorithm_repositories"
    
    id = Column(String, primary_key=True, index=True)
    algorithm_id = Column(String, ForeignKey("algorithms.id"), nullable=True, index=True)  # 关联的算法ID
    name = Column(String, nullable=False, index=True)  # 仓库名称
    description = Column(Text, default="")  # 仓库描述
    type = Column(String, default="code")  # 仓库类型：code, model, hybrid
    repo_url = Column(String, nullable=False)  # Git仓库URL
    branch = Column(String, default="main")  # 分支名称
    local_path = Column(String, default="")  # 本地存储路径
    status = Column(String, default="active", index=True)  # 状态
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    algorithm = relationship("Algorithm", back_populates="repository", uselist=False)


class AlgorithmService(Base):
    """算法服务模型"""
    __tablename__ = "algorithm_services"
    
    id = Column(String, primary_key=True, index=True)
    service_id = Column(String, unique=True, nullable=False, index=True)  # 服务ID
    name = Column(String, nullable=False, index=True)  # 服务名称
    algorithm_name = Column(String, nullable=False)  # 算法名称
    version = Column(String, nullable=False)  # 版本
    host = Column(String, nullable=False)  # 主机地址
    port = Column(Integer, nullable=False)  # 端口
    api_url = Column(String, nullable=False)  # API地址
    status = Column(String, default="stopped", index=True)  # 状态：running, stopped, error, restarting
    config = Column(JSON, default=dict)  # 服务配置
    start_time = Column(DateTime(timezone=True), nullable=True)  # 启动时间
    last_heartbeat = Column(DateTime(timezone=True), nullable=True)  # 最后心跳时间
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())


# 添加Algorithm模型的repository关系
Algorithm.repository = relationship("AlgorithmRepository", back_populates="algorithm", uselist=False)
