// Copyright 2025 The Forgejo Authors. All rights reserved.
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package config

import (
	"encoding/json"
	"fmt"
	"net/url"
	"os"

	"code.forgejo.org/forgejo/runner/v13/internal/pkg/labels"
	"github.com/google/go-cmp/cmp"
	gouuid "github.com/google/uuid"
)

const RegistrationWarning = "This file is automatically generated by forgejo-runner. Do not edit it manually unless you know what you are doing. Removing this file will cause act runner to re-register as a new runner."

// Registration is the registration information for a runner
type Registration struct {
	Warning string `json:"WARNING"` // Warning message to display, it's always the RegistrationWarning constant

	ID      int64    `json:"id"`
	UUID    string   `json:"uuid"`
	Name    string   `json:"name"`
	Token   string   `json:"token"`
	Address string   `json:"address"`
	Labels  []string `json:"labels"`
}

func FromRegistration(config *Config) error {
	reg, err := LoadRegistration(config.Runner.File)
	if os.IsNotExist(err) {
		return nil
	} else if err != nil {
		return fmt.Errorf("failed to load registration file: %w", err)
	}

	if len(config.Server.Connections) != 0 {
		return fmt.Errorf("server connection conflict between %q and config; only one config file can provide server connections", config.Runner.File)
	}

	parsedURL, err := url.ParseRequestURI(reg.Address)
	if err != nil {
		return fmt.Errorf("malformed `url` %q: %w", reg.Address, err)
	}
	if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
		return fmt.Errorf("invalid scheme in `url` %q: only http and https supported", reg.Address)
	}
	parsedUUID, err := gouuid.Parse(reg.UUID)
	if err != nil {
		return fmt.Errorf("malformed `uuid` %q: %w", reg.UUID, err)
	}
	var parsedLabels labels.Labels
	for _, label := range reg.Labels {
		parsedLabel, err := labels.Parse(label)
		if err != nil {
			return fmt.Errorf("malformed `label` %q: %w", label, err)
		}
		parsedLabels = append(parsedLabels, parsedLabel)
	}

	if config.Server.Connections == nil {
		config.Server.Connections = make(map[string]*Connection)
	}
	config.Server.Connections[reg.Name] = &Connection{
		URL:           parsedURL,
		UUID:          parsedUUID,
		Token:         reg.Token,
		Labels:        parsedLabels,
		labelPriority: overrideIfPossible,
	}

	return nil
}

func LoadRegistration(file string) (*Registration, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var reg Registration
	if err := json.NewDecoder(f).Decode(&reg); err != nil {
		return nil, err
	}

	return &reg, nil
}

func isEqualRegistration(file string, reg *Registration) (bool, error) {
	existing, err := LoadRegistration(file)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	return cmp.Equal(*reg, *existing), nil
}

func SaveRegistration(file string, reg *Registration) error {
	equal, err := isEqualRegistration(file, reg)
	if err != nil {
		return err
	}
	if equal {
		return nil
	}
	f, err := os.Create(file)
	if err != nil {
		return err
	}
	defer f.Close()

	reg.Warning = RegistrationWarning

	enc := json.NewEncoder(f)
	enc.SetIndent("", "  ")
	return enc.Encode(reg)
}
