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

"""
脚本执行日志数据模型
记录脚本执行过程、结果和性能指标
"""

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


class VWEDScriptExecutionLog(Base):
    """脚本执行日志模型"""
    
    __tablename__ = 'vwed_script_execution_log'
    
    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')
    execution_type = Column(String(50), nullable=False, comment='执行类型: start_service, stop_service, function_call, api_call')
    function_name = Column(String(255), comment='执行的函数名')
    input_params = Column(JSON, comment='输入参数')
    output_result = Column(JSON, comment='输出结果')
    status = Column(String(20), nullable=False, comment='执行状态: running, success, failed, timeout')
    error_message = Column(Text, comment='错误信息')
    error_traceback = Column(Text, comment='错误堆栈')
    start_time = Column(DateTime, nullable=False, default=func.now(), comment='开始时间')
    end_time = Column(DateTime, comment='结束时间')
    duration_ms = Column(Integer, comment='执行时长(毫秒)')
    memory_usage_mb = Column(Float, comment='内存使用(MB)')
    cpu_usage_percent = Column(Float, comment='CPU使用率(%)')
    log_level = Column(String(20), default='INFO', comment='日志级别: DEBUG, INFO, WARNING, ERROR')
    tags = Column(JSON, comment='标签信息')
    created_at = Column(DateTime, nullable=False, default=func.now(), comment='创建时间')
    
    # 关联关系
    script_file = relationship("VWEDScriptFile", backref="execution_logs")
    
    def __repr__(self):
        return f"<VWEDScriptExecutionLog(id={self.id}, script_id='{self.script_id}', status='{self.status}')>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'script_id': self.script_id,
            'file_id': self.file_id,
            'execution_type': self.execution_type,
            'function_name': self.function_name,
            'input_params': self.input_params,
            'output_result': self.output_result,
            'status': self.status,
            'error_message': self.error_message,
            'error_traceback': self.error_traceback,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'duration_ms': self.duration_ms,
            'memory_usage_mb': self.memory_usage_mb,
            'cpu_usage_percent': self.cpu_usage_percent,
            'log_level': self.log_level,
            'tags': self.tags,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }
    
    def mark_completed(self, success=True, result=None, error=None):
        """标记执行完成"""
        import datetime
        self.end_time = datetime.datetime.now()
        if self.start_time:
            delta = self.end_time - self.start_time
            self.duration_ms = int(delta.total_seconds() * 1000)
        
        if success:
            self.status = 'success'
            self.output_result = result
        else:
            self.status = 'failed'
            self.error_message = str(error) if error else '未知错误'