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

"""
在线脚本相关模型
包含脚本主表、版本表和日志表
"""

import datetime
from sqlalchemy import Column, String, Integer, DateTime, Text, Boolean, ForeignKey
from sqlalchemy.dialects.mysql import LONGTEXT, BIT
from sqlalchemy.orm import relationship
from data.models.base import BaseModel


class VWEDScript(BaseModel):
    """
    在线脚本模型
    对应vwed_script表
    功能：存储系统中的Python脚本
    """
    __tablename__ = 'vwed_script'

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_general_ci',
        'info': {'order_by': 'created_at DESC'}
    }
    id = Column(String(255), primary_key=True, nullable=False, comment='脚本唯一标识')
    name = Column(String(255), nullable=False, comment='脚本名称')
    folder_path = Column(String(255), default='/', comment='脚本所在目录路径')
    file_name = Column(String(255), nullable=False, comment='脚本文件名')
    description = Column(String(500), comment='脚本功能描述')
    code = Column(LONGTEXT, nullable=False, comment='脚本代码内容')
    version = Column(Integer, nullable=False, default=1, comment='当前版本号')
    status = Column(Integer, nullable=False, default=1, comment='状态(1:启用, 0:禁用)')
    is_public = Column(BIT(1), nullable=False, default=1, comment='是否公开')
    tags = Column(String(255), comment='标签，用于分类查询')
    created_by = Column(String(255), comment='创建者')
    updated_by = Column(String(255), comment='最后更新者')
    test_params = Column(LONGTEXT, comment='测试参数(JSON格式)')

    # 关联关系
    versions = relationship("VWEDScriptVersion", back_populates="script", cascade="all, delete-orphan")
    logs = relationship("VWEDScriptLog", back_populates="script", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<VWEDScript(id='{self.id}', name='{self.name}', version='{self.version}')>"


class VWEDScriptVersion(BaseModel):
    """
    脚本版本模型
    对应vwed_script_version表
    功能：保存脚本历史版本
    """
    __tablename__ = 'vwed_script_version'

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_general_ci'
    }

    id = Column(String(255), primary_key=True, nullable=False, comment='版本记录ID')
    script_id = Column(String(255), ForeignKey('vwed_script.id', name='vwed_script_version_ibfk_1'), nullable=False, comment='关联的脚本ID')
    version = Column(Integer, nullable=False, comment='版本号')
    code = Column(LONGTEXT, nullable=False, comment='该版本代码')
    change_log = Column(Text, comment='版本变更说明')
    created_by = Column(String(255), comment='创建者')
    # 关联关系
    script = relationship("VWEDScript", back_populates="versions")

    def __repr__(self):
        return f"<VWEDScriptVersion(script_id='{self.script_id}', version='{self.version}')>"


class VWEDScriptLog(BaseModel):
    """
    脚本执行日志模型
    对应vwed_script_log表
    功能：记录脚本执行情况
    """
    __tablename__ = 'vwed_script_log'

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_general_ci'
    }

    id = Column(String(255), primary_key=True, nullable=False, comment='日志ID')
    script_id = Column(String(255), ForeignKey('vwed_script.id'), nullable=False, comment='关联的脚本ID')
    version = Column(Integer, nullable=False, comment='使用的脚本版本')
    task_record_id = Column(String(255), comment='关联的任务记录ID')
    block_record_id = Column(String(255), comment='关联的任务块记录ID')
    input_params = Column(LONGTEXT, comment='输入参数(JSON格式)')
    output_result = Column(LONGTEXT, comment='输出结果(JSON格式)')
    status = Column(Integer, comment='执行状态(1:成功, 0:失败)')
    error_message = Column(Text, comment='错误信息')
    execution_time = Column(Integer, comment='执行耗时(毫秒)')
    started_on = Column(DateTime, comment='开始时间')
    ended_on = Column(DateTime, comment='结束时间')

    # 关联关系
    script = relationship("VWEDScript", back_populates="logs")

    def __repr__(self):
        return f"<VWEDScriptLog(id='{self.id}', script_id='{self.script_id}', status='{self.status}')>" 