package agentd

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)

// logf is the agent's structured-ish logger. It deliberately never logs
// dp_uuids, peers' addresses or any payload — only operational events — to honour
// the no-log policy.
func logf(format string, args ...any) {
	log.Printf("[pangolin-agent] "+format, args...)
}

// atomicWrite writes data to a temp file in the same directory and renames it into
// place, so a crash mid-write never leaves a truncated config/state file.
func atomicWrite(path string, data []byte, perm os.FileMode) error {
	dir := filepath.Dir(path)
	tmp, err := os.CreateTemp(dir, ".tmp-*")
	if err != nil {
		return fmt.Errorf("agentd: temp file: %w", err)
	}
	tmpName := tmp.Name()
	defer os.Remove(tmpName) // no-op if the rename succeeded
	if _, err := tmp.Write(data); err != nil {
		tmp.Close()
		return fmt.Errorf("agentd: write temp: %w", err)
	}
	if err := tmp.Chmod(perm); err != nil {
		tmp.Close()
		return fmt.Errorf("agentd: chmod temp: %w", err)
	}
	if err := tmp.Close(); err != nil {
		return fmt.Errorf("agentd: close temp: %w", err)
	}
	if err := os.Rename(tmpName, path); err != nil {
		return fmt.Errorf("agentd: rename temp: %w", err)
	}
	return nil
}

// SystemdRestarter restarts the sing-box unit via `systemctl restart`.
type SystemdRestarter struct {
	Unit string // e.g. "sing-box"
}

// Restart runs `systemctl restart <unit>`.
func (r SystemdRestarter) Restart(ctx context.Context) error {
	unit := r.Unit
	if unit == "" {
		unit = "sing-box"
	}
	cmd := exec.CommandContext(ctx, "systemctl", "restart", unit)
	if out, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("agentd: restart %s: %w: %s", unit, err, out)
	}
	return nil
}
