import fs from "fs"; import path from "path"; import { TGResult, TGScore, Nation } from "../types"; import { oppositeNation } from "./nations"; const HISTORY_DIR = path.join(__dirname, "../../data/tg-history"); function historyKey(date: string, slot: number): string { return `${date}-${String(slot).padStart(2, "0")}`; } function historyPath(key: string): string { return path.join(HISTORY_DIR, `${key}.json`); } export function loadResult(date: string, slot: number): TGResult | null { try { return JSON.parse(fs.readFileSync(historyPath(historyKey(date, slot)), "utf8")); } catch { return null; } } export function saveResult(result: TGResult): void { if (!fs.existsSync(HISTORY_DIR)) fs.mkdirSync(HISTORY_DIR, { recursive: true }); const key = historyKey(result.date, result.slot); fs.writeFileSync(historyPath(key), JSON.stringify(result, null, 2)); } export function upsertScore(score: TGScore): void { const result = loadResult(score.date, score.slot) ?? { slot: score.slot, date: score.date, confirmed: false, nationKD: { source: "Procyon" as Nation, capella: { k: 0, d: 0 }, procyon: { k: 0, d: 0 }, }, scores: [], }; // Overwrite existing score for this player+slot result.scores = result.scores.filter( (s) => !(s.usermapKey === score.usermapKey && s.slot === score.slot && s.date === score.date) ); result.scores.push(score); saveResult(result); } export function setNationKD( date: string, slot: number, sourceNation: Nation, k: number, d: number ): TGResult { const result = loadResult(date, slot) ?? { slot, date, confirmed: false, nationKD: { source: sourceNation, capella: { k: 0, d: 0 }, procyon: { k: 0, d: 0 } }, scores: [], }; result.nationKD.source = sourceNation; const other = oppositeNation(sourceNation); result.nationKD[sourceNation.toLowerCase() as "capella" | "procyon"] = { k, d }; result.nationKD[other.toLowerCase() as "capella" | "procyon"] = { k: d, d: k }; saveResult(result); return result; } export function listRecentResults(limit = 10): TGResult[] { if (!fs.existsSync(HISTORY_DIR)) return []; return fs.readdirSync(HISTORY_DIR) .filter((f) => f.endsWith(".json")) .sort() .reverse() .slice(0, limit) .map((f) => { try { return JSON.parse(fs.readFileSync(path.join(HISTORY_DIR, f), "utf8")) as TGResult; } catch { return null; } }) .filter(Boolean) as TGResult[]; } export function todayString(): string { return new Date().toISOString().slice(0, 10); }