import type { Health, Item, Result } from "./types"; async function request(path: string, init?: RequestInit): Promise { let res: Response; try { res = await fetch(path, init); } catch { throw new Error("Can't reach the KhmerSense server. Is the backend running?"); } const body = await res.json().catch(() => ({})); if (!res.ok) throw new Error(typeof body.detail === "string" ? body.detail : `Something went wrong (${res.status}).`); return body as T; } const json = (data: unknown): RequestInit => ({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); export const api = { health: () => request("/api/health"), analyzeTexts: (texts: string[]) => request("/api/analyze", json({ texts })), analyzeYouTube: (url: string, limit: number, order: "relevance" | "time") => request("/api/youtube", json({ url, limit, order })), analyzeFile: (file: File) => { const fd = new FormData(); fd.append("file", file); return request("/api/upload", { method: "POST", body: fd }); }, }; /** CSV with a UTF-8 BOM so Excel shows Khmer correctly. */ export function downloadCsv(items: Item[], name: string) { const esc = (v: unknown) => `"${String(v ?? "").replace(/"/g, '""')}"`; const head = ["comment", "sentiment", "confidence", "language", "likes", "date"]; const rows = items.map((i) => [i.text, i.label, i.confidence, i.language, i.likes ?? "", i.published_at ?? ""].map(esc).join(",")); const blob = new Blob(["" + [head.join(","), ...rows].join("\r\n")], { type: "text/csv;charset=utf-8" }); const a = Object.assign(document.createElement("a"), { href: URL.createObjectURL(blob), download: name }); a.click(); URL.revokeObjectURL(a.href); } export const SAMPLE_COMMENTS = [ "វីដេអូនេះល្អណាស់ អរគុណបងៗ", "This video is so helpful, thank you!", "សំឡេងតិចពេក ស្តាប់មិនសូវឮទេ", "video ល្អណាស់ bro 👍", "Waste of time, the title is clickbait", "ពេលណាចេញភាគបន្ទាប់?", "Love the editing and the music 😍", "មិនល្អទេ ធុញណាស់", "ok", "បងពូកែណាស់ ចង់រៀនបន្ថែមទៀត", "The sound quality is bad in the second half", "Where was this filmed?", ];