import { writable } from 'svelte/store';
import { browser } from '$app/environment';

/**
 * Create config store with runtime configuration
 */
function createConfigStore() {
  const { subscribe, set, update } = writable({
    apiUrl: '',
    loaded: false,
    error: null,
  });

  return {
    subscribe,

    /**
     * Load configuration from config.json or env variables
     */
    load: async () => {
      if (!browser) return;

      try {
        const response = await fetch('/config.json');
        if (!response.ok) {
          throw new Error(`Failed to load config: ${response.status}`);
        }
        const config = await response.json();
        set({
          apiUrl: config.apiUrl || '',
          loaded: true,
          error: null,
        });
      } catch (err) {
        // Fallback to env variable if config.json not found
        const envApiUrl = import.meta.env.VITE_API_URL;
        if (envApiUrl) {
          set({
            apiUrl: envApiUrl,
            loaded: true,
            error: null,
          });
        } else {
          console.error('Failed to load config:', err);
          set({
            apiUrl: '',
            loaded: true,
            error: err.message,
          });
        }
      }
    },

    /**
     * Get current API URL
     * @returns {string}
     */
    getApiUrl: () => {
      let url = '';
      subscribe((config) => {
        url = config.apiUrl;
      })();
      return url;
    },
  };
}

export const config = createConfigStore();
