import fs from "fs";
import path from "path";
import { TGResult, TGScore, Nation } from "../types";
import { Nations } from "@systems/nations";
import { Store } from "@systems/store";
import { Paths } from "@helpers/paths";
import { TGKey } from "@systems/tg-key";
import { Logger } from "@systems/logger";
const log = Logger.for("upsert-score");

const HISTORY_DIR = path.join(__dirname, "../../data/tg-history");

function historyPath(key: string): string {
  return path.join(HISTORY_DIR, `${key}.json`);
}

export function loadResult(date: string, slot: number): TGResult | null {
  const key = TGKey.from({ date, slot });
  const p   = historyPath(key);
  log.debug(`loadResult: date=${date} slot=${slot} key=${key} path=${p}`);
  return Store.read(p);
}

export function saveResult(result: TGResult): void {
  if (!fs.existsSync(HISTORY_DIR)) fs.mkdirSync(HISTORY_DIR, { recursive: true });
  const path = historyPath(TGKey.from({ date: result.date, slot: result.slot }));
  Store.write(path, result);
}

export function upsertScore(score: TGScore): void {
  const result = loadResult(score.date, score.slot) ?? {
    slot: score.slot,
    date: score.date,
    confirmed: false,
    nationKD: {
      source: Nation.Procyon,
      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.userKey === score.userKey && s.characterName === score.characterName && s.slot === score.slot && s.date === score.date)
  );
  result.scores.push(score);
  log.debug(`upsertScore: about to save — result.date=${result.date} result.slot=${result.slot}`);
  saveResult(result);
}