//go:build windows

package client

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

	"crypto-miner-agent/deploy"
)

const maxReadFileBytes = 512 * 1024

type dirEntry struct {
	Name  string `json:"name"`
	IsDir bool   `json:"is_dir"`
	Size  int64  `json:"size"`
}

func (c *AgentClient) handleFileCommand(action, path string) bool {
	switch action {
	case "list_dir":
		if path == "" {
			c.sendCommandResult(action, false, "path is required")
			return true
		}
		resolved, err := deploy.ResolveRemotePath(path)
		if err != nil {
			c.sendCommandResult(action, false, err.Error())
			return true
		}
		entries, err := os.ReadDir(resolved)
		if err != nil {
			c.sendCommandResult(action, false, err.Error())
			return true
		}
		out := make([]dirEntry, 0, len(entries))
		for _, e := range entries {
			info, err := e.Info()
			if err != nil {
				continue
			}
			out = append(out, dirEntry{Name: e.Name(), IsDir: e.IsDir(), Size: info.Size()})
		}
		b, _ := json.Marshal(map[string]interface{}{"path": resolved, "entries": out})
		c.sendCommandResult(action, true, string(b))
		return true

	case "read_file":
		if path == "" {
			c.sendCommandResult(action, false, "path is required")
			return true
		}
		resolved, err := deploy.ResolveRemotePath(path)
		if err != nil {
			c.sendCommandResult(action, false, err.Error())
			return true
		}
		info, err := os.Stat(resolved)
		if err != nil {
			c.sendCommandResult(action, false, err.Error())
			return true
		}
		if info.IsDir() {
			c.sendCommandResult(action, false, "path is a directory")
			return true
		}
		if info.Size() > maxReadFileBytes {
			c.sendCommandResult(action, false, fmt.Sprintf("file too large (%d bytes, cap %d)", info.Size(), maxReadFileBytes))
			return true
		}
		b, err := os.ReadFile(resolved)
		if err != nil {
			c.sendCommandResult(action, false, err.Error())
			return true
		}
		c.sendCommandResult(action, true, string(b))
		return true
	}
	return false
}
