/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
package event

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/logger/logger"
	"jobarranger2/src/libs/golibs/uds"
)

// Send EventData to the Unix Domain Socket
func (e *EventData) SendViaUDS(unixSocketPath string) error {
	// Get UDS Client
	udsClient := uds.CreateUdsClient(unixSocketPath, 1)
	udsConn, err := udsClient.Connect()
	if err != nil {
		return fmt.Errorf("uds client connect error: %w", err)
	}
	defer udsConn.Close()

	// Send Data
	if err := udsConn.Send(e); err != nil {
		return fmt.Errorf("uds client send error: %w", err)
	}

	// Assuming the server does not return any response

	return nil
}

/* Json file */

// creates a new EventData instance with initialized fields
func NewJobnetLoadingEvent(eventName, nextProcessName, managerName string) *EventData {
	event := &EventData{}
	event.Event.Name = eventName
	event.Event.UniqueKey = fmt.Sprintf("%s_%d", managerName, time.Now().UnixNano())
	event.NextProcess.Name = nextProcessName
	event.NextProcess.Data = make(map[string]any)
	return event
}

// updates the NextProcess.Data map with provided key-value pairs
func (e *EventData) SetNextProcessData(data map[string]any) error {
	if data == nil {
		return fmt.Errorf("cannot set nil data")
	}

	for key, value := range data {
		if existing, ok := e.NextProcess.Data[key]; !ok || existing != value {
			e.NextProcess.Data[key] = value
		}
	}

	return nil
}

// appends a new query string to the EventData's Queries slice
func (e *EventData) AddQuery(queries string) {
	e.Queries = append(e.Queries, queries)
}

// configures the file transfer paths including source, destination, and Unix Domain Socket path in the EventData structure
func (e *EventData) AddFilePaths(source, destination string) {
	e.Transfer.Files = append(e.Transfer.Files, FileEntry{
		Source:      source,
		Destination: destination,
	})
}

func (e *EventData) SetUDSSocketPath(socketPath string) {
	e.Transfer.UDS.SocketPath = socketPath
}

// create json file and insert data
// e.Transfer.Files[0].Source must be the directory path of source file; source file name will be generated
func (e *EventData) WriteToFile() error {
	//  Validate required fields exist and are correct type
	if e.NextProcess.Data == nil {
		return fmt.Errorf("NextProcess.Data is not initialized")
	}

	innerJobnetID, ok1 := e.NextProcess.Data["inner_jobnet_main_id"].(int64)
	innerJobID, ok2 := e.NextProcess.Data["inner_job_id"].(int64)
	if !ok1 || !ok2 {
		return fmt.Errorf("missing or invalid job IDs in NextProcess.Data")
	}

	dirPath := e.Transfer.Files[0].Source

	// Generate filename and path
	timestamp := time.Now().Format("20060102150405")
	filename := fmt.Sprintf("%d_%d_%s.json", innerJobnetID, innerJobID, timestamp)
	fullPath := filepath.Join(dirPath, filename)
	e.Transfer.Files[0].Source = fullPath

	// Marshal JSON with pretty printing
	jsonBytes, err := json.MarshalIndent(e, "", "    ")
	if err != nil {
		return fmt.Errorf("failed to marshal JSON: %w", err)
	}

	//  Write file with proper permissions
	if err := os.WriteFile(fullPath, jsonBytes, 0644); err != nil {
		return fmt.Errorf("failed to write file: %w", err)
	}

	// fmt.Printf("JSON successfully written to %s\n", fullPath)
	return nil
}

// CheckRunCountFile ensures the directory and file <runcountFolderPath>/<innerJobnetMainID>/<innerJobID_runCount>
func CheckRunCountFile(runcountFolderPath string, innerJobnetMainID, innerJobID uint64, runCount, methodFlag int) (bool, error) {
	// Full path: <runcountFolderPath>/<innerJobnetMainID>
	targetDir := filepath.Join(runcountFolderPath, fmt.Sprintf("%d", innerJobnetMainID))
	return CheckRunCountFileCore(targetDir, innerJobID, runCount, methodFlag)
}

// CheckRunCountFile ensures the directory and file <runcountFolderPath>/<innerJobnetMainID>/<innerJobID_runCount>
func CheckRunCountFileAgent(runcountFolderPath, serverID string, innerJobID uint64, runCount, methodFlag int) (bool, error) {
	// Full path: <runcountFolderPath>/<innerJobnetMainID>
	targetDir := filepath.Join(runcountFolderPath, serverID)
	return CheckRunCountFileCore(targetDir, innerJobID, runCount, methodFlag)
}

func CheckRunCountFileCore(targetDir string, innerJobID uint64, runCount, methodFlag int) (bool, error) {
	funcName := "CheckRunCountFileCore"
	// Check if directory exists
	info, err := os.Stat(targetDir)
	if os.IsNotExist(err) {
		logger.JaLog("JAUTILS000002", logger.Logging{}, funcName, targetDir)

		// Create directory
		err := os.MkdirAll(targetDir, common.FilePermission)
		if err != nil {
			return false, fmt.Errorf("[%s] failed to create directory: %v", funcName, err) // directory creation fail
		}

		logger.JaLog("JAUTILS000003", logger.Logging{}, funcName, targetDir)
		return true, nil // new folder created

	} else if err == nil && info.IsDir() {

		logger.JaLog("JAUTILS400005", logger.Logging{}, funcName, targetDir) // directory already exist
	} else if err != nil {
		return false, fmt.Errorf("[%s] failed to check directory: %v", funcName, err) // directory creation fail
	} else {
		return false, fmt.Errorf("[%s] path exists but is not a directory: %s", funcName, targetDir) // directory creation fail
	}

	// File name preparation (innerJobID_runCount)
	fileName := fmt.Sprintf("%d_%d", innerJobID, runCount)
	filePath := filepath.Join(targetDir, fileName)

	// Check if file exists
	if _, err := os.Stat(filePath); !os.IsNotExist(err) {
		// File exists
		logger.JaLog("JAUTILS000005", logger.Logging{}, funcName, targetDir)
		if methodFlag == int(common.MethodRerun) { // re_run
			return true, nil // file exist but continue
		}
		return false, nil
	}

	return true, nil // file does not exist
}

// CreateRunCountFile ensures the directory <runcountFolderPath>/<innerJobnetMainID>/
func CreateRunCountFile(runcountFolderPath string, innerJobnetMainID, innerJobID uint64, runCount int) error {
	// Full path: <runcountFolderPath>/<innerJobnetMainID>
	targetDir := filepath.Join(runcountFolderPath, fmt.Sprintf("%d", innerJobnetMainID))
	return CreateRunCountFileCore(targetDir, innerJobID, runCount)
}

func CreateRunCountFileAgent(runcountFolderPath, serverID string, innerJobID uint64, runCount int) error {
	// Full path: <runcountFolderPath>/<innerJobnetMainID>
	targetDir := filepath.Join(runcountFolderPath, serverID)
	return CreateRunCountFileCore(targetDir, innerJobID, runCount)
}

func CreateRunCountFileCore(targetDir string, innerJobID uint64, runCount int) error {
	funcName := "CreateRunCountFileCore"

	// Create file with name innerJobID_RunCount
	fileName := fmt.Sprintf("%d_%d", innerJobID, runCount)
	filePath := filepath.Join(targetDir, fileName)

	// File doesn't exist, create it
	file, err := os.Create(filePath)
	if err != nil {
		return fmt.Errorf("[%s] failed to create file: %v", funcName, err)
	}
	defer file.Close() // Ensure the file gets closed after creation

	logger.JaLog("JAUTILS400006", logger.Logging{}, funcName, filePath)

	return nil
}

// DeleteRunCountFile deletes the file <runcountFolderPath>/<InnerJobnetMainID>/<InnerJobID>_<RunCount>
func DeleteRunCountFile(runcountFolderPath string, innerJobnetMainID uint64) error {
	return DeleteRunCountFileCore(runcountFolderPath, innerJobnetMainID, nil)
}

func DeleteOldRunCountFile(runcountFolderPath string, innerJobnetMainID uint64, days int) error {
	return DeleteRunCountFileCore(runcountFolderPath, innerJobnetMainID, func(info os.FileInfo) bool {
		modTime := info.ModTime()
		cutoff := time.Now().AddDate(0, 0, -days)

		return modTime.Before(cutoff)
	})
}

func DeleteRunCountFileCore(runcountFolderPath string, innerJobnetMainID uint64, check func(info os.FileInfo) bool) error {
	funcName := "DeleteRunCountFileCore"

	targetDir := filepath.Join(runcountFolderPath, fmt.Sprintf("%d", innerJobnetMainID))

	// Check if file exists first
	if _, err := os.Stat(targetDir); os.IsNotExist(err) {
		// File not found → not an error
		logger.JaLog("JAUTILS300002", logger.Logging{}, funcName, targetDir)
		return nil

	} else if err != nil {
		return fmt.Errorf("[%s] Error checking directory: %v", funcName, err)
	}

	if check == nil {
		// Delete file
		err := os.RemoveAll(targetDir)
		if err != nil {
			return fmt.Errorf("[%s] failed to delete directory: %v", funcName, err)
		}

		logger.JaLog("JAUTILS000004", logger.Logging{}, funcName, targetDir)
		return nil
	}

	// Conditional delete → iterate entries
	entries, err := os.ReadDir(targetDir)
	if err != nil {
		return fmt.Errorf("[%s] failed to read directory: %v", funcName, err)
	}

	for _, entry := range entries {
		info, err := entry.Info()
		if err != nil {
			return fmt.Errorf("[%s] failed to get file info: %v", funcName, err)
		}

		if check(info) {
			filePath := filepath.Join(targetDir, entry.Name())
			if err := os.Remove(filePath); err != nil {
				return fmt.Errorf("[%s] failed to delete file %s: %v", funcName, filePath, err)
			}

			logger.JaLog("JAUTILS000004", logger.Logging{}, funcName, filePath)
		}
	}

	return nil
}
