package executor

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/safedep/dry/log"
	"github.com/safedep/dry/usefulerror"
	"github.com/safedep/dry/utils"
	"github.com/safedep/pmg/config"
	"github.com/safedep/pmg/errcodes"
	"github.com/safedep/pmg/internal/audit"
	"github.com/safedep/pmg/sandbox"
	"github.com/safedep/pmg/sandbox/platform"
	"github.com/safedep/pmg/sandbox/util"
)

type applySandboxConfig struct {
	sb sandbox.Sandbox
	rt *sandbox.ExecutionContext
}

type applySandboxOpt func(*applySandboxConfig)

// WithSandbox sets the sandbox to use for the command.
// When not set, the sandbox will be determined by the platform.
func WithSandbox(sb sandbox.Sandbox) applySandboxOpt {
	return func(c *applySandboxConfig) {
		c.sb = sb
	}
}

// WithExecutionContext provides runtime data known only at spawn time
// (e.g. the PMG proxy address) to the sandbox driver.
func WithExecutionContext(rt *sandbox.ExecutionContext) applySandboxOpt {
	return func(c *applySandboxConfig) {
		c.rt = rt
	}
}

// ApplySandbox applies sandbox isolation to the command if sandbox mode is enabled.
// This is a helper function used by both guard and proxy flows to avoid code duplication.
//
// This is a security sensitive operation. If sandbox is enabled via. config but not available on the platform,
// it will return an error to avoid running the command without sandbox protection.
func ApplySandbox(ctx context.Context, cmd *exec.Cmd, pmName string, opts ...applySandboxOpt) (*sandbox.ExecutionResult, error) {
	cfg := config.Get()

	if !cfg.Config.Sandbox.Enabled {
		return sandbox.NewExecutionResult(), nil
	}

	applyConfig := &applySandboxConfig{}
	for _, opt := range opts {
		opt(applyConfig)
	}

	registry, err := sandbox.NewProfileRegistry(sandbox.WithUserProfileDir(cfg.SandboxProfileDir()))
	if err != nil {
		return nil, fmt.Errorf("failed to create profile registry: %w", err)
	}

	var policy *sandbox.SandboxPolicy

	if cfg.SandboxProfileOverride != "" {
		log.Debugf("Using sandbox profile override: %s", cfg.SandboxProfileOverride)

		policy, err = registry.GetProfile(cfg.SandboxProfileOverride)
		if err != nil {
			return nil, usefulerror.NewUsefulError().
				WithCode(errcodes.InvalidArgument).
				WithHumanError(fmt.Sprintf("Failed to load sandbox profile override: %s", cfg.SandboxProfileOverride)).
				WithHelp("Please verify the sandbox profile path and try again.").
				WithAdditionalHelp("See more at: https://github.com/safedep/pmg/blob/main/docs/sandbox.md").
				Wrap(err)
		}
	} else {
		log.Debugf("Looking up sandbox policy for %s", pmName)

		// When a policy is not configured for a package manager, we error out
		// This is to avoid running the command without sandbox protection.
		// To bypass sandbox for a specific package manager, users should explicitly
		// disable for the package manager in the config.
		policyRef, exists := cfg.Config.Sandbox.PolicyFor(pmName)
		if !exists {
			return nil, usefulerror.NewUsefulError().
				WithCode(errcodes.NotFound).
				WithHumanError(fmt.Sprintf("No sandbox policy configured for %s", pmName)).
				WithHelp("Please configure a sandbox policy for this package manager in the config file.").
				WithAdditionalHelp("See https://github.com/safedep/pmg/blob/main/docs/sandbox.md for more information.").
				Wrap(fmt.Errorf("no sandbox policy configured for %s", pmName))
		}

		// The policy is explicitly disabled for this package manager, so we skip sandbox
		if !policyRef.Enabled {
			log.Warnf("sandbox policy %s is explicitly disabled for %s, skipping sandbox", policyRef.Profile, pmName)
			return sandbox.NewExecutionResult(), nil
		}

		log.Debugf("Loading sandbox policy %s", policyRef.Profile)

		// Check if there is a template for the policy and use it if it exists
		// This is a way to override a built-in profile or create a custom profile.
		if template, exists := cfg.Config.Sandbox.PolicyTemplates[policyRef.Profile]; exists {
			if filepath.IsAbs(template.Path) {
				policy, err = registry.GetProfile(template.Path)
				if err != nil {
					return nil, fmt.Errorf("failed to load sandbox policy %s: %w", template.Path, err)
				}
			} else {
				policyPath := filepath.Join(cfg.ConfigDir(), template.Path)
				policy, err = registry.GetProfile(policyPath)
				if err != nil {
					return nil, fmt.Errorf("failed to load sandbox policy %s: %w", policyPath, err)
				}
			}
		} else {
			// Load the policy from the registry by name
			policy, err = registry.GetProfile(policyRef.Profile)
			if err != nil {
				return nil, fmt.Errorf("failed to load sandbox policy %s: %w", policyRef.Profile, err)
			}
		}
	}

	log.Debugf("Loaded sandbox policy %s", policy.Name)

	// Apply the per-repo project overlay (saved via `pmg sandbox allow`). When
	// global_lockdown is set, overlays are ignored so the locked baseline is
	// authoritative. An empty cwd is tolerated by ResolveRepoRoot's callers
	// downstream, so swallow a Getwd error here.
	cwd, _ := os.Getwd()
	if repoRoot, repoErr := sandbox.ResolveRepoRoot(cwd); repoErr != nil {
		log.Warnf("Project overlay: resolve repo root: %v", repoErr)
	} else if _, err := applyProjectOverlay(policy, cfg.SandboxOverlayDir(), repoRoot, cfg.IsLocked()); err != nil {
		log.Warnf("Project overlay: apply: %v", err)
		// A failed overlay load means the user's saved allowances were silently
		// dropped. Echo to stderr so users at normal verbosity see why their
		// sandbox is more restrictive than expected.
		fmt.Fprintf(os.Stderr, "pmg: warning: project overlay could not be applied: %v\n", err)
	}

	// Apply runtime --sandbox-allow overrides to the policy before execution
	if len(cfg.SandboxAllowOverrides) > 0 {
		applyRuntimeOverrides(policy, cfg.SandboxAllowOverrides)
		logSandboxOverrides(policy.Name, cfg.SandboxAllowOverrides)
	}

	if !policy.AppliesToPackageManager(pmName) {
		return nil, fmt.Errorf("sandbox policy %s does not apply to %s", policy.Name, pmName)
	}

	var sb sandbox.Sandbox
	if applyConfig.sb != nil {
		sb = applyConfig.sb
	} else {
		sb, err = platform.NewSandbox()
		if err != nil {
			return nil, fmt.Errorf("sandbox not available on this platform: %v", err)
		}
	}

	if !sb.IsAvailable() {
		return nil, usefulerror.NewUsefulError().
			WithCode(errcodes.InvalidArgument).
			WithHumanError(fmt.Sprintf("Sandbox %s is required but not available", sb.Name())).
			WithHelp("Please install the sandbox provider and try again.").
			WithAdditionalHelp("See more at: https://github.com/safedep/pmg/blob/main/docs/sandbox.md").
			Wrap(fmt.Errorf("sandbox %s is required but not available", sb.Name()))
	}

	log.Debugf("Running %s in %s sandbox with policy %s", pmName, sb.Name(), policy.Name)

	// Scrub sensitive environment variables before the child is spawned. This
	// runs after overlay and runtime overrides are merged into the policy so
	// user allowances are honored, and is platform-independent (it filters the
	// env slice regardless of the OS sandbox driver).
	scrubbed := scrubEnv(cmd, policy)

	if _, err := sandbox.ValidateNetworkLockdown(policy, applyConfig.rt); err != nil {
		return nil, err
	}

	result, err := sb.Execute(ctx, cmd, policy, applyConfig.rt)
	if err != nil {
		return nil, fmt.Errorf("failed to setup sandbox: %w", err)
	}

	result.SetScrubbedEnvCount(scrubbed)

	return result, nil
}

// applyRuntimeOverrides applies --sandbox-allow overrides to the policy.
// Overrides append to allow lists and remove exact matches from corresponding deny lists
// so that deny rules don't shadow the explicit override. Only full-path exact matches are
// removed — glob and wildcard deny patterns are never modified to stay secure by default.
func applyRuntimeOverrides(policy *sandbox.SandboxPolicy, overrides []config.SandboxAllowOverride) {
	for _, override := range overrides {
		switch override.Type {
		case config.SandboxAllowRead:
			log.Infof("Sandbox override: allowing read access to %s", override.Value)
			policy.Filesystem.AllowRead = append(policy.Filesystem.AllowRead, override.Value)
			policy.Filesystem.DenyRead = removeExactMatch(policy.Filesystem.DenyRead, override.Value)

		case config.SandboxAllowWrite:
			log.Infof("Sandbox override: allowing write access to %s", override.Value)
			policy.Filesystem.AllowWrite = append(policy.Filesystem.AllowWrite, override.Value)
			policy.Filesystem.DenyWrite = removeExactMatch(policy.Filesystem.DenyWrite, override.Value)

		case config.SandboxAllowExec:
			log.Infof("Sandbox override: allowing execution of %s", override.Value)
			policy.Process.AllowExec = append(policy.Process.AllowExec, override.Value)
			policy.Process.DenyExec = removeExactMatch(policy.Process.DenyExec, override.Value)

		case config.SandboxAllowNetConnect:
			log.Infof("Sandbox override: allowing outbound connection to %s", override.Value)
			policy.Network.AllowOutbound = append(policy.Network.AllowOutbound, override.Value)

		case config.SandboxAllowNetBind:
			log.Infof("Sandbox override: allowing network bind on %s", override.Value)
			policy.Network.AllowBind = append(policy.Network.AllowBind, override.Value)

			// Enable AllowNetworkBind so the translator emits bind rules.
			// Without this, AllowBind entries would be ignored on some platforms.
			policy.AllowNetworkBind = utils.PtrTo(true)

		case config.SandboxAllowEnv:
			// Allow-wins: appending to Allow un-scrubs the variable regardless
			// of whether it was denied by the built-in list or a profile deny
			// glob, so (unlike the filesystem cases) there is no deny list to
			// remove an exact match from.
			log.Infof("Sandbox override: allowing environment variable %s", override.Value)
			policy.Environment.Allow = append(policy.Environment.Allow, override.Value)
		}
	}
}

// scrubEnv removes sensitive environment variables from cmd.Env per the
// resolved policy's environment section and returns how many were removed.
// It runs after project overlay and runtime overrides are merged into the
// policy, so user allowances take effect. A nil cmd.Env would mean "inherit
// the parent environment", which would defeat scrubbing, so it is populated
// from os.Environ() first.
func scrubEnv(cmd *exec.Cmd, policy *sandbox.SandboxPolicy) int {
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}

	result := util.ScrubEnv(cmd.Env, util.EnvScrubOptions{
		Allow: policy.Environment.Allow,
		Deny:  policy.Environment.Deny,
	})
	cmd.Env = result.Env

	if len(result.Removed) > 0 {
		log.Infof("Sandbox: scrubbed %d sensitive environment variable(s) from %s: %s",
			len(result.Removed), policy.Name, strings.Join(result.Removed, ", "))
	}

	return len(result.Removed)
}

// removeExactMatch removes entries from the slice that exactly match the given value.
// Glob patterns and wildcards in the slice are never matched. Only literal string
// equality is used. This keeps broad deny rules intact while allowing targeted overrides.
func removeExactMatch(slice []string, value string) []string {
	result := make([]string, 0, len(slice))
	for _, entry := range slice {
		if entry == value {
			log.Infof("Sandbox override: removing conflicting deny rule for %s", value)
			continue
		}

		result = append(result, entry)
	}

	return result
}

// applyProjectOverlay loads the per-repo overlay (when one exists) and feeds
// its entries through applyRuntimeOverrides. Returns the number of entries
// applied. A nil/missing overlay is a clean no-op. When locked, the overlay
// is ignored entirely.
func applyProjectOverlay(policy *sandbox.SandboxPolicy, overlayDir, repoRoot string, locked bool) (int, error) {
	if locked {
		log.Debugf("Project overlay: skipping under global_lockdown")
		return 0, nil
	}

	overlay, _, err := sandbox.LoadOverlayForRepo(overlayDir, repoRoot)
	if err != nil {
		return 0, fmt.Errorf("project overlay: load: %w", err)
	}
	if overlay == nil || len(overlay.Allow) == 0 {
		return 0, nil
	}

	entries := overlay.ToAllowOverrides()
	applyRuntimeOverrides(policy, entries)
	// The "+overlay" suffix tags audit events as overlay-sourced.
	logSandboxOverrides(policy.Name+"+overlay", entries)
	log.Infof("Project overlay: applied %d saved allowance(s) for %s", len(entries), repoRoot)
	return len(entries), nil
}

// logSandboxOverrides records sandbox allow overrides in the audit event log.
func logSandboxOverrides(profileName string, overrides []config.SandboxAllowOverride) {
	entries := make([]map[string]string, 0, len(overrides))
	for _, o := range overrides {
		entries = append(entries, map[string]string{
			"type":  string(o.Type),
			"value": o.Value,
		})
	}

	audit.LogSandboxOverride(profileName, entries)
}
