import { defaultModelConfig, normalizeModelConfig } from '@infiplot/core';
import type { ModelConfigMap } from '@infiplot/types';
import { Platform } from 'react-native';

const STORAGE_KEY = 'infiplot:mobile:model-config';

export { defaultModelConfig };
export type { ModelConfigMap };

let memoryStore: string | null = null;

function getWebStorage() {
  if (Platform.OS !== 'web' || typeof window === 'undefined') return null;
  return window.localStorage;
}

export async function readModelConfig(): Promise<ModelConfigMap> {
  try {
    const storage = getWebStorage();
    const raw = storage ? storage.getItem(STORAGE_KEY) : memoryStore;
    if (!raw) return defaultModelConfig;
    return normalizeModelConfig(JSON.parse(raw));
  } catch {
    return defaultModelConfig;
  }
}

export async function writeModelConfig(config: ModelConfigMap): Promise<ModelConfigMap> {
  const normalized = normalizeModelConfig(config);
  const serialized = JSON.stringify(normalized);

  try {
    const storage = getWebStorage();
    if (storage) {
      storage.setItem(STORAGE_KEY, serialized);
    } else {
      memoryStore = serialized;
    }
  } catch {
    memoryStore = serialized;
  }

  return normalized;
}

export async function clearModelConfig(): Promise<ModelConfigMap> {
  try {
    const storage = getWebStorage();
    if (storage) storage.removeItem(STORAGE_KEY);
  } catch {
    // Storage can be unavailable in private sessions.
  }

  memoryStore = null;
  return defaultModelConfig;
}
