package httpapi

import (
	"net/http"

	gatewaydocs "github.com/easyai/easyai-ai-gateway/apps/api/docs"
	"github.com/easyai/easyai-ai-gateway/apps/api/internal/skillbundle"
)

const (
	opsManagementSkillDownloadPath = "/api/v1/public/skills/ai-gateway-ops-management/download"
	apiDocsJSONPath                = "/api/v1/openapi.json"
	apiDocsYAMLPath                = "/api/v1/openapi.yaml"
)

// getOpsManagementSkillMetadata godoc
// @Summary 获取 AI Gateway 运维管理 SKILL 元数据
// @Description 返回公开运维管理 SKILL 的名称、版本、模块、下载文件名和机器可读接口文档路径。
// @Tags agent-resources
// @Produce json
// @Success 200 {object} SkillBundleMetadataResponse
// @Failure 500 {object} ErrorEnvelope
// @Router /api/v1/public/skills/ai-gateway-ops-management/metadata [get]
func (s *Server) getOpsManagementSkillMetadata(w http.ResponseWriter, _ *http.Request) {
	metadata, err := skillbundle.LoadMetadata()
	if err != nil {
		s.logger.Error("load operations skill metadata failed", "error", err)
		writeError(w, http.StatusInternalServerError, "operations skill metadata unavailable")
		return
	}
	writeJSON(w, http.StatusOK, opsManagementSkillMetadataResponse(metadata))
}

// downloadOpsManagementSkill godoc
// @Summary 下载 AI Gateway 运维管理 SKILL
// @Description 下载可交给 Agent 使用的 ai-gateway-ops-management ZIP 包。
// @Tags agent-resources
// @Produce application/zip
// @Success 200 {file} binary
// @Failure 500 {object} ErrorEnvelope
// @Router /api/v1/public/skills/ai-gateway-ops-management/download [get]
func (s *Server) downloadOpsManagementSkill(w http.ResponseWriter, _ *http.Request) {
	metadata, err := skillbundle.LoadMetadata()
	if err != nil {
		s.logger.Error("load operations skill metadata failed", "error", err)
		writeError(w, http.StatusInternalServerError, "operations skill metadata unavailable")
		return
	}
	archive, err := skillbundle.BuildArchive()
	if err != nil {
		s.logger.Error("build operations skill archive failed", "error", err)
		writeError(w, http.StatusInternalServerError, "operations skill download unavailable")
		return
	}
	w.Header().Set("Content-Type", "application/zip")
	w.Header().Set("Content-Disposition", `attachment; filename="`+skillbundle.FileName(metadata)+`"`)
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(archive)
}

// apiDocsJSON godoc
// @Summary 获取 AI Gateway Swagger JSON
// @Description 返回当前构建内嵌的完整机器可读 Swagger JSON，供 Agent 在 SKILL references 未覆盖接口时查询。
// @Tags agent-resources
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/openapi.json [get]
func (s *Server) apiDocsJSON(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(gatewaydocs.SwaggerJSON)
}

// apiDocsYAML godoc
// @Summary 获取 AI Gateway Swagger YAML
// @Description 返回当前构建内嵌的完整机器可读 Swagger YAML。
// @Tags agent-resources
// @Produce application/yaml
// @Success 200 {string} string
// @Router /api/v1/openapi.yaml [get]
func (s *Server) apiDocsYAML(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "application/yaml; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(gatewaydocs.SwaggerYAML)
}

func opsManagementSkillMetadataResponse(metadata skillbundle.Metadata) SkillBundleMetadataResponse {
	return SkillBundleMetadataResponse{
		Name:            metadata.Name,
		Version:         metadata.Version,
		DisplayName:     skillbundle.DisplayName,
		Modules:         metadata.Modules,
		FileName:        skillbundle.FileName(metadata),
		DownloadPath:    opsManagementSkillDownloadPath,
		APIDocsJSONPath: apiDocsJSONPath,
		APIDocsYAMLPath: apiDocsYAMLPath,
	}
}
