import Store from 'electron-store';

// ---------------------------------------------------------------------------
// Local agent config — stored entirely on the FE, never on the backend.
// ---------------------------------------------------------------------------

export interface LocalAgentLocalConfig {
  id: string;
  name: string;
  directory: string;
  dataTypes: string[];
  /** Structured extraction config produced by the Journey setup flow. */
  agentConfig: Record<string, unknown> | null;
  scheduleCron: string;
  enabled: boolean;
  lastRunAt: number | null;
}

// ---------------------------------------------------------------------------
// Format preferences — stored locally, never sent to LLM
// ---------------------------------------------------------------------------

export interface FormatPrefs {
  timezone: string;
  dateFormat: string; // 'dd/MM/yyyy' | 'MM/dd/yyyy' | 'yyyy-MM-dd'
  timeFormat: '12h' | '24h';
}

// ---------------------------------------------------------------------------
// App settings (electron-store shape)
// ---------------------------------------------------------------------------

interface AppSettings {
  sidebarCollapsed: boolean;
  encryptedTokens: Record<string, string>;
  /** Base URL of the AdiuvAI backend API (e.g. 'http://localhost:8000'). */
  backendUrl: string;
  /**
   * Stable device identifier — UUID v4 generated once on first launch and
   * persisted forever.  Used to bind local agents to the machine they were
   * configured on.
   */
  deviceId: string;
  /** Cached daily brief — regenerated once per day or when relevant data changes. */
  dailyBriefCache: { content: string; date: string } | null;
  /** Locally-managed agent configurations. */
  localAgents: LocalAgentLocalConfig[];
  /** OS-detected display format preferences. */
  formatPrefs: FormatPrefs | null;
  /** UI language code (e.g. 'en', 'it', 'es', 'fr', 'de'). */
  uiLanguage: string;
  /** Timeline zoom level. */
  timelineZoom: ZoomLevel;
}

export type ZoomLevel = 'day' | 'week' | 'month';

let _store: Store<AppSettings> | null = null;

export function getStore(): Store<AppSettings> {
  if (!_store) {
    _store = new Store<AppSettings>({
      defaults: {
        sidebarCollapsed: false,
        encryptedTokens: {},
        backendUrl: 'http://localhost:8000',
        deviceId: '',
        dailyBriefCache: null,
        localAgents: [],
        formatPrefs: null,
        uiLanguage: 'en',
        timelineZoom: 'day',
      },
    });
  }
  return _store;
}

/**
 * Returns the stable device ID, generating and persisting a new UUID v4 on
 * first call.  Subsequent calls always return the same value.
 */
export function getDeviceId(): string {
  const store = getStore();
  let id = store.get('deviceId');
  if (!id) {
    id = crypto.randomUUID();
    store.set('deviceId', id);
  }
  return id;
}

// ---------------------------------------------------------------------------
// Local agent helpers
// ---------------------------------------------------------------------------

export function getLocalAgents(): LocalAgentLocalConfig[] {
  return getStore().get('localAgents');
}

export function getLocalAgent(id: string): LocalAgentLocalConfig | undefined {
  return getLocalAgents().find((a) => a.id === id);
}

export function saveLocalAgent(agent: LocalAgentLocalConfig): void {
  const agents = getLocalAgents();
  const idx = agents.findIndex((a) => a.id === agent.id);
  if (idx >= 0) {
    agents[idx] = agent;
  } else {
    agents.push(agent);
  }
  getStore().set('localAgents', agents);
}

export function deleteLocalAgent(id: string): void {
  const agents = getLocalAgents().filter((a) => a.id !== id);
  getStore().set('localAgents', agents);
}

// ---------------------------------------------------------------------------
// Format preference helpers
// ---------------------------------------------------------------------------

export function getFormatPrefs(): FormatPrefs | null {
  return getStore().get('formatPrefs', null);
}

export function setFormatPrefs(prefs: FormatPrefs): void {
  getStore().set('formatPrefs', prefs);
}

// ---------------------------------------------------------------------------
// UI language helpers
// ---------------------------------------------------------------------------

export function getUiLanguage(): string {
  return getStore().get('uiLanguage', 'en');
}

export function setUiLanguage(lang: string): void {
  getStore().set('uiLanguage', lang);
}

export function getTimelineZoom(): ZoomLevel {
  const v = getStore().get('timelineZoom', 'day');
  return v === 'day' || v === 'week' || v === 'month' ? v : 'day';
}

export function setTimelineZoom(level: ZoomLevel): void {
  getStore().set('timelineZoom', level);
}
