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

"""
函数注册记录数据模型
记录脚本注册的自定义函数信息
"""

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 VWEDScriptFunctionRegistration(Base):
    """函数注册记录模型"""
    
    __tablename__ = 'vwed_script_function_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')
    function_name = Column(String(255), nullable=False, comment='函数名')
    handler_name = Column(String(255), nullable=False, comment='处理函数名(实际函数名)')
    description = Column(Text, comment='函数描述')
    parameters = Column(JSON, comment='参数定义: [{"name": "param1", "type": "str", "required": true}]')
    return_schema = Column(JSON, comment='返回值格式定义')
    is_async = Column(Boolean, default=False, comment='是否为异步函数')
    is_active = Column(Boolean, default=True, comment='是否激活')
    call_count = Column(Integer, default=0, comment='调用次数')
    last_called_at = Column(DateTime, comment='最后调用时间')
    average_execution_time_ms = Column(Integer, comment='平均执行时间(毫秒)')
    success_count = Column(Integer, default=0, comment='成功执行次数')
    error_count = Column(Integer, default=0, comment='错误次数')
    tags = Column(JSON, comment='函数标签')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='注册时间')
    
    # 关联关系
    script_file = relationship("VWEDScriptFile", backref="function_registrations")
    
    def __repr__(self):
        return f"<VWEDScriptFunctionRegistration(id={self.id}, name='{self.function_name}')>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'script_id': self.script_id,
            'file_id': self.file_id,
            'function_name': self.function_name,
            'handler_name': self.handler_name,
            'description': self.description,
            'parameters': self.parameters,
            'return_schema': self.return_schema,
            'is_async': self.is_async,
            '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_execution_time_ms': self.average_execution_time_ms,
            'success_count': self.success_count,
            'error_count': self.error_count,
            'success_rate': self.success_rate,
            'tags': self.tags,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }
    
    @property
    def success_rate(self):
        """计算成功率"""
        if self.call_count == 0:
            return 0.0
        return round((self.success_count / self.call_count) * 100, 2)
    
    def update_call_stats(self, execution_time_ms, success=True):
        """更新调用统计"""
        import datetime
        self.call_count += 1
        self.last_called_at = datetime.datetime.now()
        
        if success:
            self.success_count += 1
        else:
            self.error_count += 1
        
        # 更新平均执行时间
        if self.average_execution_time_ms is None:
            self.average_execution_time_ms = execution_time_ms
        else:
            total_time = self.average_execution_time_ms * (self.call_count - 1) + execution_time_ms
            self.average_execution_time_ms = int(total_time / self.call_count)