package com.agent.management.model.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.PrePersist;
import jakarta.persistence.Table;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * Agent 对话消息日志子表（结构化）。
 *
 * <p>对应设计文档 {@code docs/design/agent-chat-page-design.md} §4.1.3。
 * 每条 assistant 消息的思考过程日志按"行"结构化存储，与
 * {@code WorkflowRunNode.logs} 元素一一对应。</p>
 *
 * <p>设计动机（vs 单一 {@code logs_json} 字段）：</p>
 * <ul>
 *   <li>写入流式：O(1) 行级 INSERT</li>
 *   <li>按 kind 查询：{@code WHERE kind='tool_call'} 走索引</li>
 *   <li>无单字段超大问题（思考流数千字时）</li>
 *   <li>与前端 {@code buildReplayNode} 直接对接：取所有行按 seq 排序即还原 {@code ExecutionLog[]}</li>
 * </ul>
 */
@Data
@Entity
@Table(name = "chat_message_log", indexes = {
        @Index(name = "idx_chat_log_message", columnList = "message_id, seq"),
        @Index(name = "idx_chat_log_kind", columnList = "message_id, kind")
})
public class ChatMessageLog {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "message_id", nullable = false)
    private Long messageId;

    /** 同一消息内的顺序（从 0 递增） */
    @Column(name = "seq", nullable = false)
    private Integer seq;

    /**
     * 与 {@code ExecutionLog.Type} 对应：
     * thinking / status / tool_call / tool_result / todo_update / clarify_request / step / tool_progress / info / error
     */
    @Column(name = "kind", nullable = false, length = 24)
    private String kind;

    /** 内容文本（与 ExecutionLog.content 同义） */
    @Column(name = "content", columnDefinition = "TEXT")
    private String content;

    /** 仅 kind=tool_call/tool_result 有 */
    @Column(name = "tool_name", length = 128)
    private String toolName;

    /** 扩展元数据 JSON：如 clarifyId/choices、todo 列表 JSON 等 */
    @Column(name = "meta_json", columnDefinition = "TEXT")
    private String metaJson;

    @Column(name = "created_at", nullable = false)
    private LocalDateTime createdAt;

    @PrePersist
    protected void onCreate() {
        if (createdAt == null) createdAt = LocalDateTime.now();
        if (seq == null) seq = 0;
    }
}
