package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
)

func filePathForTmpJobServer(uniqueID string) string {
	TrapperLogger.JaLog("JATRAPPERMANAGER400001", "filePathForTmpJobServer")
	dir := filepath.Dir(filepath.Join(server.Options.TmpDir, string(common.TrapperManagerProcess), "job"))
	jobFileName := uniqueID + ".job"
	return filepath.Join(dir, "job", jobFileName)
}

// addUidToJobFile appends the given uid to the specified job file, creating it if it doesn't exist.
func addUidToJobFile(path, uid string) error {
	funcname := "addUidToJobFile"
	TrapperLogger.JaLog("JATRAPPERMANAGER400001", funcname)
	f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return fmt.Errorf("failed to open job file: %w", err)
	}
	defer f.Close()

	if _, err := f.WriteString(uid + "\n"); err != nil {
		return fmt.Errorf("failed to write UID to job file: %w", err)
	}
	TrapperLogger.JaLog("JATRAPPERMANAGER400009", path, uid)
	return nil
}

// ReadLastLineOrNew reads the last line of the file at filePath.
// If the file does not exist, it returns "new".
func readLastLineOrNew(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if errors.Is(err, os.ErrNotExist) {
		return "new", nil
	}
	if err != nil {
		return "", fmt.Errorf("error opening file: %w", err)
	}
	defer file.Close()

	var lastLine string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lastLine = scanner.Text()
	}
	if err := scanner.Err(); err != nil {
		return "", fmt.Errorf("error reading file: %w", err)
	}

	return strings.TrimSpace(lastLine), nil
}
