package store

// AgentConfig 存储 room 维度的 agent 配置（SOUL.md / AGENT.md / TEAM.md）
type AgentConfig struct {
	RoomID    string
	AgentName string // agent 名称，TEAM.md 用 "__team__"
	FileType  string // "soul" | "agent" | "team_doc" | "memory"
	Content   string
	UpdatedAt string
}

const agentConfigTeamDoc = "__team__"

func (s *Store) GetAgentConfig(roomID, agentName, fileType string) (string, error) {
	var content string
	err := s.db.QueryRow(
		`SELECT content FROM agent_configs WHERE room_id = ? AND agent_name = ? AND file_type = ?`,
		roomID, agentName, fileType,
	).Scan(&content)
	if err != nil {
		return "", err
	}
	return content, nil
}

func (s *Store) SetAgentConfig(roomID, agentName, fileType, content string) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	_, err := s.db.Exec(
		`INSERT INTO agent_configs (room_id, agent_name, file_type, content)
		 VALUES (?, ?, ?, ?)
		 ON CONFLICT(room_id, agent_name, file_type)
		 DO UPDATE SET content = excluded.content, updated_at = datetime('now')`,
		roomID, agentName, fileType, content,
	)
	return err
}

// GetRoomAgentConfigs 获取某个 room 下所有 agent 配置
func (s *Store) GetRoomAgentConfigs(roomID string) ([]AgentConfig, error) {
	rows, err := s.db.Query(
		`SELECT room_id, agent_name, file_type, content, updated_at FROM agent_configs WHERE room_id = ?`,
		roomID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var configs []AgentConfig
	for rows.Next() {
		var c AgentConfig
		if err := rows.Scan(&c.RoomID, &c.AgentName, &c.FileType, &c.Content, &c.UpdatedAt); err != nil {
			return nil, err
		}
		configs = append(configs, c)
	}
	return configs, nil
}
