// Package cispec is de blue-ci-cd.yml-specificatie.
// De infopagina en GET /api/v1/ci/spec gebruiken allebei Build, zodat de
// tekst en de presets niet uit elkaar lopen.
package cispec

import (
	"bytes"
	"encoding/json"

	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/images"
)

// Doc is het document dat de pagina tekent en de API teruggeeft.
type Doc struct {
	File     string    `json:"file"`
	Example  string    `json:"example"`
	Sections []Section `json:"sections"`
}

// Section is één blok: sleutelwoorden, variabelen, verschillen of presets.
type Section struct {
	ID        string     `json:"id"`
	Title     string     `json:"title"`
	Intro     string     `json:"intro,omitempty"`
	Kind      string     `json:"kind"`
	Items     []Item     `json:"items,omitempty"`
	Variables []Variable `json:"variables,omitempty"`
	Lines     []string   `json:"lines,omitempty"`
	Presets   []Preset   `json:"presets,omitempty"`
}

// Item is één sleutelwoord.
type Item struct {
	Name    string `json:"name"`
	Summary string `json:"summary"`
}

// Variable is een voorgedefinieerde CI_-variabele.
// Scope is both, container of mr en blijft in het Engels, ook als de pagina vertaald is.
type Variable struct {
	Name    string `json:"name"`
	Scope   string `json:"scope"`
	Where   string `json:"where"`
	Summary string `json:"summary"`
}

// Preset is één image-alias zoals Steve die bouwt of mapt.
type Preset struct {
	Name    string   `json:"name"`
	Runtime string   `json:"runtime"`
	From    string   `json:"from"`
	Tools   []string `json:"tools"`
	Mode    string   `json:"mode"`
}

const example = `image: bluegit/base
unit:
  stage: test
  image: bluegit/node
  script:
    - node --version
plain:
  stage: test
  image: node:22
  script:
    - node --version
`

// Build maakt het document in lang. presets nil gebruikt de ingebouwde lijst.
func Build(lang i18n.Lang, presets []images.Preset) Doc {
	if presets == nil {
		presets = images.Builtin()
	}
	t := func(key string) string { return i18n.T(lang, key) }
	kw := func(name, key string) Item { return Item{Name: name, Summary: t(key)} }
	where := map[string]string{
		"both":      t("info.where.both"),
		"container": t("info.where.container"),
		"mr":        t("info.where.mr"),
	}
	variable := func(name, scope string) Variable {
		return Variable{Name: name, Scope: scope, Where: where[scope], Summary: t("info.var." + name)}
	}
	doc := Doc{
		File:    "blue-ci-cd.yml",
		Example: example,
		Sections: []Section{
			{
				ID: "pipeline", Title: t("info.sec.pipeline"), Kind: "keywords",
				Items: []Item{
					kw("stages", "info.kw.stages"),
					kw("variables", "info.kw.variables"),
					kw("image", "info.kw.image"),
					kw("default", "info.kw.default"),
					kw("include", "info.kw.include"),
					kw("before_script", "info.kw.before_script"),
					kw("after_script", "info.kw.after_script"),
					kw("cache", "info.kw.cache"),
					kw("workflow", "info.kw.workflow"),
					kw("jobs", "info.kw.jobs"),
				},
			},
			{
				ID: "jobs", Title: t("info.sec.job"), Kind: "keywords",
				Items: []Item{
					kw("stage", "info.kw.stage"),
					kw("image", "info.kw.image"),
					kw("before_script", "info.kw.before_script"),
					kw("script", "info.kw.script"),
					kw("after_script", "info.kw.after_script"),
					kw("needs", "info.kw.needs"),
					kw("rules", "info.kw.rules"),
					kw("only", "info.kw.only"),
					kw("except", "info.kw.except"),
					kw("when", "info.kw.when"),
					kw("allow_failure", "info.kw.allow_failure"),
					kw("artifacts", "info.kw.artifacts"),
					kw("cache", "info.kw.cache"),
					kw("resource_group", "info.kw.resource_group"),
					kw("timeout", "info.kw.timeout"),
					kw("retry", "info.kw.retry"),
					kw("parallel", "info.kw.parallel"),
					kw("services", "info.kw.services"),
					kw("environment", "info.kw.environment"),
					kw("interruptible", "info.kw.interruptible"),
					kw("tags", "info.kw.tags"),
					kw("extends", "info.kw.extends"),
				},
			},
			{
				ID: "rules", Title: t("info.sec.rules"), Kind: "keywords",
				Intro: t("info.rules.intro"),
				Items: []Item{
					kw("if", "info.kw.if"),
					kw("changes", "info.kw.changes"),
					kw("exists", "info.kw.exists"),
					kw("when", "info.kw.when"),
				},
			},
			{
				ID: "variables", Title: t("info.sec.variables"), Kind: "variables",
				Variables: []Variable{
					variable("CI", "both"),
					variable("CI_CONFIG_PATH", "both"),
					variable("CI_SERVER_NAME", "both"),
					variable("CI_COMMIT_SHA", "both"),
					variable("CI_COMMIT_SHORT_SHA", "both"),
					variable("CI_COMMIT_REF", "both"),
					variable("CI_COMMIT_REF_NAME", "both"),
					variable("CI_COMMIT_REF_SLUG", "both"),
					variable("CI_COMMIT_TITLE", "both"),
					variable("CI_COMMIT_TIMESTAMP", "both"),
					variable("CI_COMMIT_BRANCH", "both"),
					variable("CI_COMMIT_TAG", "both"),
					variable("CI_DEFAULT_BRANCH", "both"),
					variable("CI_PIPELINE_ID", "both"),
					variable("CI_PIPELINE_SOURCE", "both"),
					variable("CI_PIPELINE_URL", "both"),
					variable("CI_PROJECT_PATH", "both"),
					variable("CI_PROJECT_NAME", "both"),
					variable("CI_PROJECT_NAMESPACE", "both"),
					variable("CI_PROJECT_URL", "both"),
					variable("CI_API_URL", "both"),
					variable("CI_JOB_ID", "container"),
					variable("CI_JOB_NAME", "container"),
					variable("CI_JOB_STAGE", "container"),
					variable("CI_JOB_URL", "container"),
					variable("CI_JOB_TOKEN", "container"),
					variable("CI_NODE_INDEX", "container"),
					variable("CI_NODE_TOTAL", "container"),
					variable("CI_ENVIRONMENT_NAME", "container"),
					variable("CI_ENVIRONMENT_URL", "container"),
					variable("CI_MERGE_REQUEST_ID", "mr"),
					variable("CI_MERGE_REQUEST_IID", "mr"),
					variable("CI_MERGE_REQUEST_TITLE", "mr"),
					variable("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", "mr"),
					variable("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", "mr"),
					variable("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "mr"),
					variable("CI_MERGE_REQUEST_TARGET_BRANCH_SHA", "mr"),
					variable("CI_MERGE_REQUEST_PROJECT_PATH", "mr"),
					variable("CI_MERGE_REQUEST_PROJECT_URL", "mr"),
				},
			},
			{
				ID: "differences", Title: t("info.sec.diff"), Kind: "list",
				Lines: []string{
					t("info.diff.file"),
					t("info.diff.runner"),
					t("info.diff.include"),
					t("info.diff.unsupported"),
					t("info.diff.services"),
					t("info.diff.env"),
					t("info.diff.retry"),
					t("info.diff.parallel"),
					t("info.diff.rules"),
					t("info.diff.mr"),
					t("info.diff.cache"),
					t("info.diff.images"),
				},
			},
			{
				ID: "presets", Title: t("info.sec.presets"), Kind: "presets",
				Intro:   t("info.presets.intro") + " " + t("info.presets.config"),
				Presets: presetDocs(presets),
			},
		},
	}
	return doc
}

func presetDocs(in []images.Preset) []Preset {
	out := make([]Preset, 0, len(in))
	for _, p := range in {
		mode := "dockerfile"
		if p.Direct != "" {
			mode = "image"
		}
		tools := p.Tools
		if tools == nil {
			tools = []string{}
		}
		out = append(out, Preset{
			Name: p.Name, Runtime: p.Runtime, From: p.From, Tools: tools, Mode: mode,
		})
	}
	return out
}

// Marshal is de JSON die de pagina in het scriptblok zet en de API schrijft.
func Marshal(doc Doc) []byte {
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(true)
	_ = enc.Encode(doc)
	return buf.Bytes()
}
