#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：deploy_log.py
模块描述：部署执行日志数据库模型定义

作者：czj
创建日期：2026-08-12
最后修改：2026-08-12
"""

from datetime import datetime
from sqlalchemy import String, Integer, Text, DateTime, Boolean, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base
from app.utils.id_generator import generate_id


class DeployLog(Base):
    """
    部署执行日志

    记录部署执行过程中的每一行输出，支持实时流式推送和持久化回看。

    Attributes:
        id (str): 日志唯一标识
        execution_id (str): 关联的执行记录 ID
        timestamp (datetime): 日志时间
        level (str): 日志级别 (INFO/WARN/ERROR/INPUT/OUTPUT)
        message (str): 日志内容
        is_sensitive (bool): 是否敏感信息
    """

    __tablename__ = "deploy_logs"

    id: Mapped[str] = mapped_column(
        String(64), primary_key=True, default=lambda: generate_id("deploy_log"),
        comment="日志唯一标识"
    )
    execution_id: Mapped[str] = mapped_column(
        String(64), ForeignKey("deploy_executions.id", ondelete="CASCADE"),
        nullable=False, index=True, comment="关联的执行记录 ID"
    )
    timestamp: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.utcnow, comment="日志时间"
    )
    level: Mapped[str] = mapped_column(
        String(10), default="INFO", comment="日志级别: INFO/WARN/ERROR/INPUT/OUTPUT"
    )
    message: Mapped[str] = mapped_column(
        Text, default="", comment="日志内容"
    )
    is_sensitive: Mapped[bool] = mapped_column(
        Boolean, default=False, comment="是否敏感信息"
    )

    # 关联执行记录
    execution: Mapped["DeployExecution"] = relationship(
        "DeployExecution", back_populates="logs"
    )

    def __repr__(self) -> str:
        return f"<DeployLog(id={self.id}, level={self.level})>"

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "execution_id": self.execution_id,
            "timestamp": self.timestamp.isoformat() if self.timestamp else None,
            "level": self.level,
            "message": self.message,
            "is_sensitive": self.is_sensitive,
        }