#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
API注册记录数据模型
记录脚本注册的API路由信息
"""

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


class VWEDScriptAPIRegistration(Base):
    """API注册记录模型"""
    
    __tablename__ = 'vwed_script_api_registration'
    
    id = Column(Integer, primary_key=True, autoincrement=True, comment='注册记录ID')
    script_id = Column(String(255), nullable=False, comment='脚本实例ID')
    file_id = Column(Integer, ForeignKey('vwed_script_file.id'), nullable=False, comment='脚本文件ID')
    route_path = Column(String(500), nullable=False, comment='路由路径')
    http_method = Column(String(20), nullable=False, comment='HTTP方法: GET, POST, PUT, DELETE等')
    handler_name = Column(String(255), nullable=False, comment='处理函数名')
    description = Column(Text, comment='接口描述')
    parameters = Column(JSON, comment='接口参数定义')
    response_schema = Column(JSON, comment='响应格式定义')
    is_active = Column(Boolean, default=True, comment='是否激活')
    call_count = Column(Integer, default=0, comment='调用次数')
    last_called_at = Column(DateTime, comment='最后调用时间')
    average_response_time_ms = Column(Integer, comment='平均响应时间(毫秒)')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='注册时间')
    
    # 关联关系
    script_file = relationship("VWEDScriptFile", backref="api_registrations")
    
    def __repr__(self):
        return f"<VWEDScriptAPIRegistration(id={self.id}, path='{self.route_path}', method='{self.http_method}')>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'script_id': self.script_id,
            'file_id': self.file_id,
            'route_path': self.route_path,
            'http_method': self.http_method,
            'handler_name': self.handler_name,
            'description': self.description,
            'parameters': self.parameters,
            'response_schema': self.response_schema,
            'is_active': self.is_active,
            'call_count': self.call_count,
            'last_called_at': self.last_called_at.isoformat() if self.last_called_at else None,
            'average_response_time_ms': self.average_response_time_ms,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }
    
    @property
    def route_key(self):
        """生成路由键"""
        return f"{self.http_method}:{self.route_path}"
    
    def update_call_stats(self, response_time_ms):
        """更新调用统计"""
        import datetime
        self.call_count += 1
        self.last_called_at = datetime.datetime.now()
        
        if self.average_response_time_ms is None:
            self.average_response_time_ms = response_time_ms
        else:
            # 计算新的平均响应时间
            total_time = self.average_response_time_ms * (self.call_count - 1) + response_time_ms
            self.average_response_time_ms = int(total_time / self.call_count)