# Check that the CUE generated by 'cue get go' is actually compatible
# with encoding and decoding values via Go's encoding/json package.

exec cue get go --local ./decls
cmp decls/p_go_gen.cue decls/p_go_gen.cue.golden

# Marshal via Go's encoding/json and validate with the generated CUE schema.
exec go run ./marshal
cmp stdout go_marshal.json
exec cue vet -c schema.cue go_marshal.json

# Export from CUE to verify that it results in the same JSON as Go did.
# This helps catch if any of the keys have been dropped or their values changed.
exec cue export ./decls
cmp stdout go_marshal.json

-- schema.cue --
package schema

import "mod.test/decls"

decls.#Root

-- go.mod --
module mod.test

go 1.21
-- cue.mod/module.cue --
module: "mod.test"
language: version: "v0.9.0"
-- decls/export.cue --
package decls

import "strings"

#Root & {
	Duration: #ValueSecond

	Strings: [
		#ErrorPrefix,
		#ResetColor,
		#UTF8,
	]
	NonUTF8ThirdByte: strings.ByteAt(#NonUTF8, 3)
}
-- decls/p.go --
package decls

import "time"

type Root struct {
	Duration time.Duration

	Strings []string

	// We can't roundtrip NonUTF8 directly because of https://cuelang.org/issue/3823.
	// Roundtrip its third byte for now, which does work.
	NonUTF8ThirdByte int
}

const ValueSecond = 3 * time.Second

const ErrorPrefix = "\033[31mError:\033[0m"
const ResetColor = "\u001b[0m"

const UTF8 = "\x30\x31\x32" // "012"
// The third byte here should not be replaced by \uFFFD, the replacement character.
const NonUTF8 = "a\xffb\xC0\xAFc\xff"
-- decls/p_go_gen.cue.golden --
// Code generated by cue get go. DO NOT EDIT.

//cue:generate cue get go mod.test/decls

package decls

#Root: {
	Duration: int @go(,time.Duration)
	Strings: [...string] @go(,[]string)

	// We can't roundtrip NonUTF8 directly because of https://cuelang.org/issue/3823.
	// Roundtrip its third byte for now, which does work.
	NonUTF8ThirdByte: int
}

#ValueSecond: int & 3000000000

#ErrorPrefix: "\u001b[31mError:\u001b[0m" // "\033[31mError:\033[0m"

#ResetColor: "\u001b[0m"

#UTF8: "012" // "\x30\x31\x32"

#NonUTF8: 'a\xffb\xc0\xafc\xff' // "a\xffb\xC0\xAFc\xff"
-- marshal/main.go --
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"mod.test/decls"
)

func main() {
	r := decls.Root{
		Duration: decls.ValueSecond,
		Strings: []string{
			decls.ErrorPrefix,
			decls.ResetColor,
			decls.UTF8,
		},
		NonUTF8ThirdByte: int(decls.NonUTF8[3]),
	}
	// Mimic the formatting of `cue export` to be able to compare bytes.
	data, err := json.MarshalIndent(r, "", "    ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", data)
}
-- go_marshal.json --
{
    "Duration": 3000000000,
    "Strings": [
        "\u001b[31mError:\u001b[0m",
        "\u001b[0m",
        "012"
    ],
    "NonUTF8ThirdByte": 192
}
