//go:build generate

package main

import (
	"bytes"
	"context"
	"io"
	"log/slog"
	"net/http"
	"os"
	"slices"
	"text/template"
	"time"

	"github.com/AdguardTeam/AdGuardDNS/internal/agdhttp"
	"github.com/AdguardTeam/golibs/errors"
	"github.com/AdguardTeam/golibs/httphdr"
	"github.com/AdguardTeam/golibs/logutil/slogutil"
	"github.com/AdguardTeam/golibs/osutil"
)

func main() {
	ctx := context.Background()
	logger := slogutil.New(nil)
	defer slogutil.RecoverAndExit(ctx, logger, osutil.ExitCodeFailure)

	c := &http.Client{
		Timeout: 10 * time.Second,
	}

	req := errors.Must(http.NewRequest(http.MethodGet, fakeECSBlocklistURL, nil))

	req.Header.Add(httphdr.UserAgent, agdhttp.UserAgent())

	resp := errors.Must(c.Do(req))
	defer slogutil.CloseAndLog(ctx, logger, resp.Body, slog.LevelError)

	errors.Check(agdhttp.CheckStatus(resp, http.StatusOK))

	out := errors.Must(os.OpenFile("./ecsblocklist.go", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o664))
	defer slogutil.CloseAndLog(ctx, logger, out, slog.LevelError)

	contents := errors.Must(io.ReadAll(resp.Body))

	lines := bytes.Split(contents, []byte("\n"))
	lines = lines[:len(lines)-1]

	slices.SortStableFunc(lines, bytes.Compare)

	tmpl := template.Must(template.New("main").Parse(tmplStr))

	errors.Check(tmpl.Execute(out, lines))
}

// fakeECSBlocklistURL is the default URL from where to get ECS fake domains.
const fakeECSBlocklistURL = `https://filters.adtidy.org/dns/fake-ecs-blacklist`

// tmplStr is the template of the generated Go code.
const tmplStr = `// Code generated by go run ./ecsblocklist_generate.go; DO NOT EDIT.

package ecscache

import "github.com/AdguardTeam/golibs/container"

// FakeECSFQDNs contains all domains that indicate ECS support, but in fact
// don't have one.
var FakeECSFQDNs = container.NewMapSet(
{{- range $_, $h := . }}
	{{ printf "%q" ( printf "%s." $h ) }},
{{- end }}
)
`
