export function formatSessionTitle(title: string | undefined): string {
	const text = typeof title === "string" ? title.trim() : "";
	return text || "未命名";
}

/** 与服务端一致的机器标签（会话 id、纯 hex 段等），不写进界面标题 */
export function isMachineSessionLabel(text: string | undefined, headerId: string): boolean {
	const t = (text ?? "").trim();
	if (!t) return true;
	if (headerId && t === headerId) return true;
	if (/^[0-9a-f]{8,}$/i.test(t)) return true;
	if (/^[0-9]{10,}$/.test(t)) return true;
	return false;
}

/** 首句截取（侧边栏兜底与顶栏回填，需与 backend/services/sessions.ts 保持一致逻辑） */
export function titleFromFirstUserMessage(text: string | undefined, maxChars = 56): string {
	const cleaned = String(text ?? "").replace(/\s+/g, " ").trim();
	if (!cleaned) return "";
	const sentenceMatch = cleaned.match(/^(.+?[。！？.!?])(\s|$)/);
	let candidate = sentenceMatch?.[1] ? sentenceMatch[1].trim() : cleaned;
	if (candidate.length > maxChars) {
		candidate = `${candidate.slice(0, maxChars).trimEnd()}…`;
	}
	return candidate;
}

export function modelKey(model: { provider: string; id: string } | undefined): string {
	return model ? `${model.provider}/${model.id}` : "";
}

export function modelLabel(model: { provider: string; id: string } | undefined): string {
	if (!model) return "";
	return `${model.provider}/${model.id}`;
}

/** 顶栏模型下拉展示：[渠道名]模型id，避免同名模型无法区分 */
export function shortModelLabel(model: { provider: string; id: string } | undefined, maxChars = 52): string {
	if (!model) return "";
	const provider = model.provider.trim();
	const id = model.id.trim();
	if (!provider) return id;
	if (!id) return `[${provider}]`;
	const prefix = `[${provider}]`;
	const combined = `${prefix}${id}`;
	if (combined.length <= maxChars) return combined;
	const idBudget = Math.max(12, maxChars - prefix.length);
	const clippedId = id.length <= idBudget ? id : id.slice(0, idBudget);
	return `${prefix}${clippedId}`;
}
