/**
 * Textos CSV desde `csv-upload-messages.{en,es}.json` (rama `csv_upload` extraída de messages/).
 * Mantener en sync al editar `messages/*.json` (p. ej. volver a exportar la clave csv_upload).
 */
import enPack from './csv-upload-messages.en.json';
import esPack from './csv-upload-messages.es.json';
import { baseLocale, getLocale } from '$lib/paraglide/runtime';

type CsvUploadPack = Record<string, unknown>;

function pickPack(): CsvUploadPack {
	let raw: string;
	try {
		raw = String(getLocale()).toLowerCase();
	} catch {
		raw = String(baseLocale).toLowerCase();
	}
	const root = raw.startsWith('en') ? enPack : esPack;
	return root as CsvUploadPack;
}

function walk(root: Record<string, unknown>, keys: string[]): unknown {
	let cur: unknown = root;
	for (const k of keys) {
		if (cur === null || typeof cur !== 'object') return undefined;
		cur = (cur as Record<string, unknown>)[k];
	}
	return cur;
}

/** Navega `csv_upload.a.b.c` a partir de `subPath` = `a.b.c`. */
export function csvMsg(subPath: string): string {
	const pack = pickPack();
	if (!pack) return subPath;
	const v = walk(pack as Record<string, unknown>, subPath.split('.'));
	return typeof v === 'string' ? v : subPath;
}

/** Sustituye `{clave}` en el string del mensaje. */
export function csvFmt(subPath: string, vars: Record<string, string | number> = {}): string {
	let s = csvMsg(subPath);
	for (const [k, val] of Object.entries(vars)) {
		s = s.replaceAll(`{${k}}`, String(val));
	}
	return s;
}
