<!-- #region DebugTool [C:3] [TYPE Component] [SEMANTICS debug, diagnostic, api, tool, test] -->
<!-- @BRIEF Component component: components/tools/DebugTool.svelte -->
<!-- @LAYER UI -->
<!--
@SEMANTICS: debug, tool, api, structure
@PURPOSE: UI component for system diagnostics and debugging API responses.
@LAYER UI
@RELATION USES -> [ToolsService]
-->
<script lang="ts">
    // [SECTION: IMPORTS]
    import { onMount } from 'svelte';
    import { api } from '../../lib/api.js';
    import { runTask, getTaskStatus } from '../../services/toolsService.js';
    import { selectedTask } from '$lib/stores.svelte.js';
    import { addToast } from '$lib/toasts.svelte.js';
    import { t } from '$lib/i18n/index.svelte.js';
    import { environmentContextStore } from '$lib/stores/environmentContext.svelte.js';
    // [/SECTION]

    let envs = [];
    let action = 'test-db-api';
    let selectedEnv = '';
    let datasetId = '';
    let sourceEnv = '';
    let targetEnv = '';
    let isRunning = false;
    let results = null;
    let pollInterval;

    // #region fetchEnvironments:Function [TYPE Function]
    /**
     * @purpose Fetches available environments.
     * @pre     API is available.
     * @post    envs variable is populated.
     * @returns {Promise<void>}
     */
    async function fetchEnvironments() {
        try {
            envs = await api.getEnvironmentsList();
            // Pre-fill source and single env with active environment, leave target empty
            const activeEnvId = environmentContextStore.value?.selectedEnvId;
            if (activeEnvId && envs.some((e) => e.id === activeEnvId)) {
                sourceEnv = activeEnvId;
                selectedEnv = activeEnvId;
            }
        } catch (e) {
            addToast($t.debug?.fetch_env_failed, 'error');
        }
    }
    // #endregion fetchEnvironments:Function

    // #region handleRunDebug:Function [TYPE Function]
    /**
     * @purpose Triggers the debug task.
     * @pre     Required fields are selected.
     * @post    Task is started and polling begins.
     * @returns {Promise<void>}
     */
    async function handleRunDebug() {
        isRunning = true;
        results = null;
        try {
            let params = { action };
            if (action === 'test-db-api') {
                if (!sourceEnv || !targetEnv) {
                    addToast($t.debug?.source_target_required, 'warning');
                    isRunning = false;
                    return;
                }
                const sEnv = envs.find(e => e.id === sourceEnv);
                const tEnv = envs.find(e => e.id === targetEnv);
                params.source_env = sEnv.name;
                params.target_env = tEnv.name;
            } else {
                if (!selectedEnv || !datasetId) {
                    addToast($t.debug?.env_dataset_required, 'warning');
                    isRunning = false;
                    return;
                }
                const env = envs.find(e => e.id === selectedEnv);
                params.env = env.name;
                params.dataset_id = parseInt(datasetId);
            }

            const task = await runTask('system-debug', params);
            selectedTask.set(task);
            startPolling(task.id);
        } catch (e) {
            isRunning = false;
            addToast(e.message, 'error');
        }
    }
    // #endregion handleRunDebug:Function

    // #region startPolling:Function [TYPE Function]
    /**
     * @purpose Polls for task completion.
     * @pre     Task ID is valid.
     * @post    Polls until success/failure.
     * @param   {string} taskId - ID of the task.
     * @returns {void}
     */
    function startPolling(taskId) {
        if (pollInterval) clearInterval(pollInterval);
        pollInterval = setInterval(async () => {
            try {
                const task = await getTaskStatus(taskId);
                selectedTask.set(task);
                if (task.status === 'SUCCESS') {
                    clearInterval(pollInterval);
                    isRunning = false;
                    results = task.result;
                    addToast($t.debug?.completed, 'success');
                } else if (task.status === 'FAILED') {
                    clearInterval(pollInterval);
                    isRunning = false;
                    addToast($t.debug?.failed, 'error');
                }
            } catch (e) {
                clearInterval(pollInterval);
                isRunning = false;
            }
        }, 2000);
    }
    // #endregion startPolling:Function

    onMount(fetchEnvironments);
</script>

<div class="space-y-6">
    <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <h3 class="text-lg font-medium text-gray-900 mb-4">{$t.debug?.title}</h3>
        
        <div class="mb-4">
            <label for="debug-action" class="block text-sm font-medium text-gray-700">{$t.debug?.action}</label>
            <select id="debug-action" bind:value={action} class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                <option value="test-db-api">{$t.debug?.test_db_api}</option>
                <option value="get-dataset-structure">{$t.debug?.get_dataset_structure}</option>
            </select>
        </div>

        {#if action === 'test-db-api'}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="src-env" class="block text-sm font-medium text-gray-700">{$t.migration?.source_env}</label>
                    <select id="src-env" bind:value={sourceEnv} class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        <option value="" disabled>{$t.debug?.select_source}</option>
                        {#each envs as env}
                            <option value={env.id}>{env.name}</option>
                        {/each}
                    </select>
                </div>
                <div>
                    <label for="tgt-env" class="block text-sm font-medium text-gray-700">{$t.migration?.target_env}</label>
                    <select id="tgt-env" bind:value={targetEnv} class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        <option value="" disabled>{$t.debug?.select_target}</option>
                        {#each envs as env}
                            <option value={env.id}>{env.name}</option>
                        {/each}
                    </select>
                </div>
            </div>
        {:else}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="debug-env" class="block text-sm font-medium text-gray-700">{$t.dashboard?.environment}</label>
                    <select id="debug-env" bind:value={selectedEnv} class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                        <option value="" disabled>{$t.common?.choose_environment}</option>
                        {#each envs as env}
                            <option value={env.id}>{env.name}</option>
                        {/each}
                    </select>
                </div>
                <div>
                    <label for="debug-ds-id" class="block text-sm font-medium text-gray-700">{$t.mapper?.dataset_id}</label>
                    <input type="number" id="debug-ds-id" bind:value={datasetId} class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
                </div>
            </div>
        {/if}

        <div class="mt-4 flex justify-end">
            <button onclick={handleRunDebug} disabled={isRunning} class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50">
                {isRunning ? $t.dashboard?.running : $t.debug?.run}
            </button>
        </div>
    </div>

    {#if results}
        <div class="bg-white shadow overflow-hidden sm:rounded-md border border-gray-200">
            <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
                <h3 class="text-lg leading-6 font-medium text-gray-900">{$t.debug?.output}</h3>
            </div>
            <div class="p-4">
                <pre class="text-xs text-gray-600 bg-gray-900 text-green-400 p-4 rounded-md overflow-x-auto h-96">{JSON.stringify(results, null, 2)}</pre>
            </div>
        </div>
    {/if}
</div>
<!-- #endregion DebugTool -->
