import type { AIProviderType } from '@genesislcap/foundation-ai';

/** A model used during a finalized cost session. */
export interface CostSessionModelEntry {
  model: string;
  /** Vendor id from `getStatus()` (e.g. `'anthropic'`, `'gemini'`). */
  provider?: AIProviderType;
}

/** Persisted snapshot of a completed assistant cost session. */
export interface CostSessionRecord {
  id: string;
  title: string;
  /** ISO-8601 timestamp when the session was finalized. */
  endedAt: string;
  costUsd: number;
  tokensConsumed: number;
  models: CostSessionModelEntry[];
}

const STORAGE_PREFIX = 'genesis-ai-assistant:cost-history:';

/** localStorage key for a host-scoped cost history list. */
export function costHistoryStorageKey(scope: string): string {
  return `${STORAGE_PREFIX}${scope}`;
}

/** Load persisted cost sessions for a scope (newest first). */
export function loadCostSessionHistory(scope: string): CostSessionRecord[] {
  if (typeof localStorage === 'undefined') return [];
  try {
    const raw = localStorage.getItem(costHistoryStorageKey(scope));
    if (!raw) return [];
    const parsed: unknown = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.filter(isCostSessionRecord);
  } catch {
    return [];
  }
}

/** Replace the persisted list for a scope. */
export function saveCostSessionHistory(scope: string, records: CostSessionRecord[]): void {
  if (typeof localStorage === 'undefined') return;
  try {
    localStorage.setItem(costHistoryStorageKey(scope), JSON.stringify(records));
  } catch {
    // Quota exceeded or private browsing — non-fatal.
  }
}

/** Prepend a record and persist. Returns the updated list. */
export function appendCostSessionRecord(
  scope: string,
  record: CostSessionRecord,
): CostSessionRecord[] {
  const records = [record, ...loadCostSessionHistory(scope)];
  saveCostSessionHistory(scope, records);
  return records;
}

/** Remove one record by id. Returns the updated list. */
export function removeCostSessionRecord(scope: string, id: string): CostSessionRecord[] {
  const records = loadCostSessionHistory(scope).filter((r) => r.id !== id);
  saveCostSessionHistory(scope, records);
  return records;
}

/** Clear all persisted records for a scope. */
export function clearCostSessionHistory(scope: string): void {
  if (typeof localStorage === 'undefined') return;
  try {
    localStorage.removeItem(costHistoryStorageKey(scope));
  } catch {
    // Non-fatal.
  }
}

/** Display date for a history row (e.g. "Jun 14, 2026"). */
export function formatCostSessionDate(iso: string): string {
  return new Intl.DateTimeFormat('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(new Date(iso));
}

function isCostSessionRecord(value: unknown): value is CostSessionRecord {
  if (typeof value !== 'object' || value == null) return false;
  const r = value as CostSessionRecord;
  return (
    typeof r.id === 'string' &&
    typeof r.title === 'string' &&
    typeof r.endedAt === 'string' &&
    typeof r.costUsd === 'number' &&
    typeof r.tokensConsumed === 'number' &&
    Array.isArray(r.models)
  );
}
