export function sceneStorageKey(sceneFile, prefix = 'demotool_scene_') {
  if (!sceneFile) return null;
  const filename = sceneFile.split('/').pop().replace(/\.json$/, '');
  return filename ? prefix + filename : null;
}

export function createSceneOverrideEnvelope(data, {
  version = 2,
  savedAt = Date.now(),
} = {}) {
  return {
    _version: version,
    _savedAt: savedAt,
    _sceneName: data?.name || '',
    data,
  };
}

export function parseSceneOverride(raw, { version = 2 } = {}) {
  if (!raw) return { status: 'missing', data: null };
  try {
    const envelope = typeof raw === 'string' ? JSON.parse(raw) : raw;
    if (!envelope || typeof envelope !== 'object') {
      return { status: 'invalid', data: null };
    }
    if (envelope._version !== version) {
      return {
        status: 'version-mismatch',
        data: null,
        storedVersion: envelope._version,
      };
    }
    return { status: 'ok', data: envelope.data || envelope };
  } catch (error) {
    return { status: 'invalid', data: null, error };
  }
}

export function collectSceneOverrides(storage, prefix = 'demotool_scene_') {
  const overrides = {};
  const errors = [];
  for (let index = 0; index < storage.length; index += 1) {
    const key = storage.key(index);
    if (!key?.startsWith(prefix)) continue;
    const raw = storage.getItem(key);
    if (!raw) continue;
    try {
      overrides[key.slice(prefix.length)] = JSON.parse(raw);
    } catch (error) {
      errors.push({ key, error });
    }
  }
  return { overrides, errors };
}
