"""API封装模型"""

from sqlalchemy import Column, String, DateTime, Text, Boolean, ForeignKey
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy.orm import relationship
from datetime import datetime
from app.models.database import Base
import uuid


class ApiEndpoint(Base):
    """API端点模型"""
    __tablename__ = "api_endpoints"
    
    id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
    name = Column(String, nullable=False, index=True)  # API名称
    description = Column(Text, default="")  # API描述
    path = Column(String, nullable=False, unique=True, index=True)  # API路径，如 /api/image-classification
    method = Column(String, default="POST")  # HTTP方法：GET, POST, PUT, DELETE
    algorithm_id = Column(String, ForeignKey("algorithms.id"), nullable=False, index=True)  # 关联的算法ID
    version_id = Column(String, ForeignKey("algorithm_versions.id"), nullable=False, index=True)  # 关联的算法版本ID
    service_id = Column(String, ForeignKey("algorithm_services.service_id"), nullable=True, index=True)  # 关联的服务ID
    
    # API配置
    config = Column(JSON, nullable=False, default={})  # API配置（超时、重试等）
    request_schema = Column(JSON, nullable=True)  # 请求参数schema
    response_schema = Column(JSON, nullable=True)  # 响应参数schema
    
    # 权限配置
    requires_auth = Column(Boolean, default=True)  # 是否需要认证
    allowed_roles = Column(JSON, default=[])  # 允许的角色列表
    rate_limit = Column(JSON, nullable=True)  # 限流配置，如 {"max_requests": 100, "window": 60}
    
    # 状态
    status = Column(String, default="active", index=True)  # 状态：active, inactive, deprecated
    is_public = Column(Boolean, default=False)  # 是否公开
    
    # 统计信息
    call_count = Column(String, default="0")  # 调用次数
    success_count = Column(String, default="0")  # 成功次数
    error_count = Column(String, default="0")  # 错误次数
    avg_response_time = Column(String, default="0.0")  # 平均响应时间
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
    updated_at = Column(DateTime(timezone=True), onupdate=datetime.utcnow)
    last_called_at = Column(DateTime(timezone=True), nullable=True)  # 最后调用时间


class ApiCallLog(Base):
    """API调用日志模型"""
    __tablename__ = "api_call_logs"
    
    id = Column(String, primary_key=True, index=True, default=lambda: str(uuid.uuid4()))
    api_endpoint_id = Column(String, ForeignKey("api_endpoints.id"), nullable=False, index=True)  # API端点ID
    user_id = Column(String, ForeignKey("users.id"), nullable=True, index=True)  # 调用用户ID
    
    # 请求信息
    request_method = Column(String, nullable=False)  # 请求方法
    request_path = Column(String, nullable=False)  # 请求路径
    request_headers = Column(JSON, nullable=True)  # 请求头
    request_body = Column(JSON, nullable=True)  # 请求体
    
    # 响应信息
    response_status = Column(String, nullable=False)  # 响应状态码
    response_body = Column(JSON, nullable=True)  # 响应体
    response_time = Column(String, nullable=False)  # 响应时间（秒）
    
    # 错误信息
    error_message = Column(Text, nullable=True)  # 错误信息
    error_type = Column(String, nullable=True)  # 错误类型
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), default=datetime.utcnow, index=True)  # 调用时间