📄 src/lib/history.ts
import { writable } from "svelte/store";
import type { Coords, HistoryEntry, Prediction } from "./types";

const STORAGE_KEY = "birdgo-history";

function load(): HistoryEntry[] {
  if (typeof localStorage === "undefined") return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? (JSON.parse(raw) as HistoryEntry[]) : [];
  } catch {
    return [];
  }
}

const store = writable<HistoryEntry[]>(load());

store.subscribe((entries) => {
  if (typeof localStorage !== "undefined") {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(entries));
  }
});

let sessionSeen = new Set<number>();

export function startSession() {
  sessionSeen = new Set();
}

export function endSession() {
  sessionSeen = new Set();
}

export function addDetection(
  p: Pick<Prediction, "labelIndex" | "confidence">,
  coords?: Coords,
) {
  if (p.confidence < 0.7) return;
  if (sessionSeen.has(p.labelIndex)) return;
  sessionSeen.add(p.labelIndex);
  store.update((entries) => [
    {
      labelIndex: p.labelIndex,
      confidence: p.confidence,
      detectedAt: new Date().toISOString(),
      coords,
    },
    ...entries,
  ]);
}

export const historyStore = { subscribe: store.subscribe };