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

"""
脚本文件数据模型
管理脚本文件的内容、版本和元数据
"""

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


class VWEDScriptFile(BaseModel):
    """脚本文件模型"""
    
    __tablename__ = 'vwed_script_file'
    
    project_id = Column(Integer, ForeignKey('vwed_script_project.id'), nullable=False, comment='所属项目ID')
    file_name = Column(String(255), nullable=False, comment='文件名')
    file_path = Column(String(500), nullable=False, comment='文件相对路径')
    file_type = Column(String(20), nullable=False, default='python', comment='文件类型: python, text, json等')
    content = Column(Text, comment='文件内容')
    size = Column(Integer, default=0, comment='文件大小(字节)')
    encoding = Column(String(20), default='utf-8', comment='文件编码')
    is_directory = Column(Boolean, default=False, comment='是否为目录')
    is_executable = Column(Boolean, default=False, comment='是否可执行')
    has_boot_function = Column(Boolean, default=False, comment='是否包含boot函数')
    status = Column(String(20), nullable=False, default='active', comment='文件状态: active, deleted')
    created_by = Column(String(100), comment='创建者')
    
    # 关联关系
    project = relationship("VWEDScriptProject", backref="files")
    
    def __repr__(self):
        return f"<VWEDScriptFile(id={self.id}, name='{self.file_name}', path='{self.file_path}')>"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'project_id': self.project_id,
            'file_name': self.file_name,
            'file_path': self.file_path,
            'file_type': self.file_type,
            'content': self.content,
            'size': self.size,
            'encoding': self.encoding,
            'is_directory': self.is_directory,
            'is_executable': self.is_executable,
            'has_boot_function': self.has_boot_function,
            'status': self.status,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
        }
    
    @property
    def full_path(self):
        """获取完整文件路径"""
        if self.project and self.project.project_path:
            return f"{self.project.project_path}/{self.file_path}"
        return self.file_path