/**
 * @internal
 * consistency/parse-qa.mjs — normalize qa_signoff.json (C15).
 *
 * Accepts:
 *   - grouped findings: findings: {critical: [...], major: [...], minor: [...], notes: [...]}
 *   - flat findings: findings: [{severity}]
 *   - legacy `issues: [{severity}]`
 *
 * Verdict closed set: {approved, approved-with-notes, rejected, needs-changes}.
 * Anything else -> 'unknown'. Accepts legacy `status` as a fallback field name.
 *
 * Output: {verdict, findings: [{severity, title, status, file}]}
 */

const KNOWN_VERDICTS = new Set(['approved', 'approved-with-notes', 'rejected', 'needs-changes'])

const SEVERITY_MAP = {
	critical: 'critical',
	blocker: 'critical',
	major: 'major',
	warning: 'major',
	warn: 'major',
	minor: 'minor',
	note: 'note',
	notes: 'note',
}

/**
 * @param {object | null | undefined} qa
 */
export function parseQaSignoff(qa) {
	if (!qa || typeof qa !== 'object') {
		return { verdict: 'unknown', findings: [] }
	}
	const verdict = normalizeVerdict(qa.verdict ?? qa.status)
	const raw = collectRaw(qa)
	const findings = []
	for (let i = 0; i < raw.length; i++) {
		const f = raw[i]
		if (!f || typeof f !== 'object') continue
		const sev = normalizeSeverity(f.severity)
		if (!sev) continue
		findings.push({
			severity: sev,
			title: typeof f.title === 'string' ? f.title : typeof f.message === 'string' ? f.message : '',
			status: typeof f.status === 'string' ? f.status.toLowerCase() : 'open',
			file: typeof f.file === 'string' ? f.file : typeof f.path === 'string' ? f.path : '',
		})
	}
	return { verdict, findings }
}

function normalizeVerdict(v) {
	if (typeof v !== 'string') return 'unknown'
	const k = v.toLowerCase().trim()
	// normalize common spellings
	const canonical = k.replace(/_/g, '-')
	return KNOWN_VERDICTS.has(canonical) ? canonical : 'unknown'
}

function collectRaw(qa) {
	const out = []
	const findings = qa.findings
	if (Array.isArray(findings)) {
		for (const f of findings) out.push(f)
	} else if (findings && typeof findings === 'object') {
		for (const [groupKey, group] of Object.entries(findings)) {
			if (!Array.isArray(group)) continue
			for (const f of group) {
				if (!f || typeof f !== 'object') continue
				out.push({ severity: f.severity ?? groupKey, ...f })
			}
		}
	}
	if (Array.isArray(qa.issues)) {
		for (const f of qa.issues) out.push(f)
	}
	return out
}

function normalizeSeverity(sev) {
	if (typeof sev !== 'string') return null
	const key = sev.toLowerCase().trim()
	return SEVERITY_MAP[key] ?? null
}
