package zddc

import (
	"regexp"
	"strings"
)

// transmittalFolderRE matches the canonical ZDDC transmittal-folder shape:
//
//	YYYY-MM-DD_<tracking> (<status>) - <title>
//
// where <tracking> has no spaces or underscores, <status> is anything inside
// parentheses, and <title> is anything after the dash. Capture groups:
//
//	1: date (YYYY-MM-DD)
//	2: tracking number (e.g. proj-EM-TRN-0042)
//	3: status (e.g. IFR, IFA, RSA, DFT)
//	4: title
var transmittalFolderRE = regexp.MustCompile(
	`^(\d{4}-\d{2}-\d{2})_([^_\s]+(?:-[^_\s]+)*)\s*\(([^)]+)\)\s*-\s*(.+)$`,
)

// ParseTransmittalFolder splits a folder basename into its ZDDC transmittal
// components. The fourth return is true iff name is a well-formed transmittal
// folder. Trailing slashes on name are tolerated.
//
// Used by handlers that need to recognise a staging-folder mkdir as a
// transmittal envelope (to mirror it under working/), and by the archive
// indexer that scans for transmittal folders on disk.
func ParseTransmittalFolder(name string) (date, tracking, status, title string, ok bool) {
	name = strings.TrimRight(name, "/")
	m := transmittalFolderRE.FindStringSubmatch(name)
	if m == nil {
		return "", "", "", "", false
	}
	return m[1], m[2], m[3], m[4], true
}

// IsTrnOrSubTracking reports whether tracking contains a "-TRN-" or "-SUB-"
// segment (case-insensitive). These two tracking types are the ones whose
// staging folders get a paired drafting folder under working/.
//
// "-MDL-" and other tracking types do NOT match — MDL deliverables are
// tracked via per-party mdl/ rows, not via the working↔staging mirror.
func IsTrnOrSubTracking(tracking string) bool {
	upper := strings.ToUpper(tracking)
	return strings.Contains(upper, "-TRN-") || strings.Contains(upper, "-SUB-")
}
