// [DEF:stores_module:Module]
// @TIER:      STANDARD
// @SEMANTICS: state, stores, svelte, plugins, tasks
// @PURPOSE: Global state management using Svelte stores.
// @LAYER: UI-State

import { writable } from 'svelte/store';
import { api } from './api.js';

// [DEF:plugins:Data]
// @PURPOSE: Store for the list of available plugins.
export const plugins = writable([]);
// [/DEF:plugins:Data]

// [DEF:tasks:Data]
// @PURPOSE: Store for the list of tasks.
export const tasks = writable([]);
// [/DEF:tasks:Data]

// [DEF:selectedPlugin:Data]
// @PURPOSE: Store for the currently selected plugin.
export const selectedPlugin = writable(null);
// [/DEF:selectedPlugin:Data]

// [DEF:selectedTask:Data]
// @PURPOSE: Store for the currently selected task.
export const selectedTask = writable(null);
// [/DEF:selectedTask:Data]

// [DEF:currentPage:Data]
// @PURPOSE: Store for the current page.
export const currentPage = writable('dashboard');
// [/DEF:currentPage:Data]

// [DEF:taskLogs:Data]
// @PURPOSE: Store for the logs of the currently selected task.
export const taskLogs = writable([]);
// [/DEF:taskLogs:Data]

// [DEF:fetchPlugins:Function]
// @PURPOSE: Fetches plugins from the API and updates the plugins store.
// @PRE: None.
// @POST: plugins store is updated with data from the API.
export async function fetchPlugins() {
    try {
        console.log("[stores.fetchPlugins][Action] Fetching plugins.");
        const data = await api.getPlugins();
        console.log("[stores.fetchPlugins][Coherence:OK] Plugins fetched context={{'count': " + data.length + "}}");
        plugins.set(data);
    } catch (error) {
        console.error(`[stores.fetchPlugins][Coherence:Failed] Error fetching plugins context={{'error': '${error}'}}`);
    }
}
// [/DEF:fetchPlugins:Function]

// [DEF:fetchTasks:Function]
// @PURPOSE: Fetches tasks from the API and updates the tasks store.
// @PRE: None.
// @POST: tasks store is updated with data from the API.
export async function fetchTasks() {
    try {
        console.log("[stores.fetchTasks][Action] Fetching tasks.");
        const data = await api.getTasks();
        console.log("[stores.fetchTasks][Coherence:OK] Tasks fetched context={{'count': " + data.length + "}}");
        tasks.set(data);
    } catch (error) {
        console.error(`[stores.fetchTasks][Coherence:Failed] Error fetching tasks context={{'error': '${error}'}}`);
    }
}
// [/DEF:fetchTasks:Function]
// [/DEF:stores_module:Module]