package backup

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

	"gitea.dooplex.hu/admin/felhom-controller/internal/appbackup"
)

// Tier-2 SECONDARY capture-set resolution (Task 3b, architecture §2/§8). The analog of
// offboxCaptureSet, differing only in tier (TierSecondary = mandatory + optional, vs offsite's
// mandatory-only) and surfacing target (the app's cross-drive status warning). SP-3.4's loud-gap
// discipline is identical: a structurally-refused or on-disk-missing MANDATORY path is detected here
// and surfaced in BOTH the English log and the Hungarian per-app warning — never a silent gap.

// tier2Leg is one source→dest mirror leg. DestRel is the v2-layout relpath ("hdd/<rel>" |
// "userdata/<rel>"), slash-form, joined under backups/secondary/<stack>/ by the engine.
type tier2Leg struct {
	Src     string              // absolute source dir
	DestRel string              // v2 relpath under destBase (slash-form)
	Class   appbackup.BindClass // mandatory | optional (legacy legs are mandatory-equivalent)
}

// tier2DestRel maps a classified bind's (Root, RelPath) to its v2 dest relpath (slash-form).
// RootHDD → hdd/<rel>; RootUserdata → userdata/<rel>; rel=="" → the base itself.
func tier2DestRel(root appbackup.BindRoot, rel string) string {
	base := "hdd"
	if root == appbackup.RootUserdata {
		base = "userdata"
	}
	return filepath.ToSlash(filepath.Join(base, rel))
}

// tier2CaptureSet computes an app's tier-2 secondary mirror legs + Hungarian gap warnings, resolved
// against nsRoot (== the app's HDD_PATH, Model A). Classified apps yield the TierSecondary set
// (mandatory + optional), per-bind, into the v2 layout. Legacy / no-block / no-provider apps yield the
// resolver appdata dir(s) as mandatory-equivalent legs — the SAME capture set as v0.134.x (the SQ5
// footprint promise), mapped into the same v2 layout so restore has ONE reader. Missing/refused
// mandatory paths are stat-filtered + surfaced loudly (§7-H).
func (m *Manager) tier2CaptureSet(stack, nsRoot string) (legs []tier2Leg, warns []string) {
	// Classified path.
	if m.stackProvider != nil {
		if binds, has := m.stackProvider.GetStackClassifiedBinds(stack); has {
			cs := appbackup.ComputeCaptureSet(binds, has, appbackup.TierSecondary, nsRoot)
			var gaps []string
			for _, sk := range cs.Skipped {
				if sk.Class == appbackup.ClassMandatory {
					m.logger.Printf("[ERROR] [backup] Tier 2 %s: mandatory path refused by a structural guard (%s): %s/%s — NOT in the secondary copy",
						stack, sk.Reason, sk.Root, sk.RelPath)
					gaps = append(gaps, sk.RelPath)
				}
			}
			for _, p := range cs.Paths {
				if _, err := os.Stat(p.Abs); err != nil {
					if p.Class == appbackup.ClassMandatory {
						m.logger.Printf("[WARN] [backup] Tier 2 %s: mandatory data path missing on disk, skipped: %s", stack, p.Abs)
						gaps = append(gaps, p.RelPath)
					}
					continue // optional-missing is silent (not a gap)
				}
				legs = append(legs, tier2Leg{Src: p.Abs, DestRel: tier2DestRel(p.Root, p.RelPath), Class: p.Class})
			}
			if len(gaps) > 0 {
				warns = append(warns, fmt.Sprintf("Figyelmeztetés: a(z) %s alkalmazás egyes adatmappái nem kerültek a másodlagos mentésbe: %s.",
					stack, strings.Join(gaps, ", ")))
			}
			return legs, warns
		}
	}
	// Legacy path: the resolver appdata dir(s) → hdd/appdata/<name> legs (mandatory-equivalent for SSD
	// purposes — the resolver set IS the app's state). N>1 dirs now succeed (one leg each; the v0.131.0
	// errTier2MultiDir refusal is lifted structurally). Preserve the F-S2 declared-but-absent WARN.
	declared := m.tier2AppDataBindsPresent(stack, nsRoot)
	for _, name := range m.appDataDirNames(stack, nsRoot) {
		src := AppDataDir(nsRoot, name)
		if _, err := os.Stat(src); err != nil {
			if declared {
				m.logger.Printf("[WARN] [backup] Tier 2 %s: compose declares appdata dir %q but it is absent at %s — leg skipped",
					stack, name, src)
			}
			continue
		}
		legs = append(legs, tier2Leg{
			Src:     src,
			DestRel: filepath.ToSlash(filepath.Join("hdd", "appdata", name)),
			Class:   appbackup.ClassMandatory,
		})
	}
	return legs, warns
}
