let workItemId = 0;
let baseAPIUrl = '';
let organizationId = '';
let projectId = '';
let projectName = '';
let userEmail = '';
let fieldsToFetch = [];

async function init() {
    try {
        console.log("SummarizeDialog: Starting initialization...");

        await IndexLibrary.InitializeSDK();
        console.log("SummarizeDialog: SDK initialized");

        // Get configuration from panel using IndexLibrary.SDK
        const config = IndexLibrary.SDK.getConfiguration();
        console.log("SummarizeDialog: Got configuration:", config);

        workItemId = config.workItemId;
        console.log("SummarizeDialog: Work item ID:", workItemId);

        // Load config.json
        const configData = await IndexLibrary.GetExtensionConfig();
        baseAPIUrl = configData.apiBaseUrl;
        console.log("SummarizeDialog: Base API URL:", baseAPIUrl);

        // Get context
        organizationId = IndexLibrary.GetAccountId();
        projectName = await IndexLibrary.GetCurrentProjectName();
        projectId = await IndexLibrary.GetCurrentProjectId();
        userEmail = IndexLibrary.GetUserEmail();

        console.log("SummarizeDialog: Got all context, generating summary...");

        // Generate summary
        await generateSummary();
    } catch (error) {
        console.error("SummarizeDialog: Initialization error:", error);
        document.getElementById('loadingContainer').innerHTML =
            '<div style="color: red; padding: 20px;">Error initializing: ' + error.message + '</div>';
    }
}

async function generateSummary() {
    document.getElementById('loadingContainer').style.display = 'block';
    const summaryContainer = document.getElementById('summaryContainer');
    summaryContainer.classList.remove('active');

    try {
        // First, check if summary already exists in database
        console.log("Checking for existing summary...");
        const getRes = await IndexLibrary.GetRequest({
            endpoint: `/api/WorkItemSummary/Get/${workItemId}`
        });

        if (getRes.ok) {
            // Summary exists, use it
            const existingSummary = await getRes.json();
            console.log("Found existing summary, displaying it");
            displaySummary(existingSummary.summary, existingSummary.lastUpdated);
            return;
        }

        // No existing summary found, generate new one
        console.log("No existing summary found, generating new one...");

        // Get configured fields
        const configRes = await IndexLibrary.GetRequest({
            endpoint: '/api/Settings/GetSummarizeConfigurations'
        });

        if (!configRes.ok) {
            throw new Error('Failed to fetch summarization configuration');
        }

        const configData = await configRes.json();
        fieldsToFetch = configData.summarizeFields
            ? configData.summarizeFields.split(',').map(f => f.trim())
            : ["System.Id", "System.Title", "System.Description", "System.State"];

        // Get work item
        const workItem = await IndexLibrary.GetWorkItemWithFields(workItemId, fieldsToFetch);

        // Build field dictionary
        const workItemFields = {};
        fieldsToFetch.forEach(field => {
            workItemFields[field] = workItem.fields[field];
        });

        // Generate new summary
        const generateRes = await IndexLibrary.PostRequest({
            endpoint: '/api/WorkItemSummary/Generate',
            body: {
                organizationId: organizationId,
                devOpsProjectId: projectId,
                devOpsProjectName: projectName,
                workItemId: workItemId,
                workItemFields: workItemFields,
                createdBy: userEmail
            }
        });

        if (!generateRes.ok) {
            const errorData = await generateRes.text();
            throw new Error(errorData || 'Failed to generate summary');
        }

        const summaryData = await generateRes.json();
        displaySummary(summaryData.summary, summaryData.lastUpdated);

    } catch (error) {
        console.error("Error:", error);
        document.getElementById('loadingContainer').innerHTML =
            '<div style="color: red;">Error: ' + error.message + '</div>';
    }
}

function displaySummary(summary, lastUpdated) {
    document.getElementById('loadingContainer').style.display = 'none';
    const summaryContainer = document.getElementById('summaryContainer');
    summaryContainer.classList.add('active');

    const formattedDate = new Date(lastUpdated).toLocaleString();
    document.getElementById('lastUpdatedDate').textContent = formattedDate;
    const summaryEl = document.getElementById('summaryContent');
    if (typeof DOMPurify === 'undefined') {
        summaryEl.textContent = summary || '';
        return;
    }
    const summaryHtml = marked.parse(summary || '');
    summaryEl.innerHTML = DOMPurify.sanitize(summaryHtml, { USE_PROFILES: { html: true } });
}

async function regenerateSummary() {
    // Force regenerate - skip database check and generate new summary
    console.log("Regenerating summary (forcing new generation)...");
    document.getElementById('loadingContainer').style.display = 'block';
    const summaryContainer = document.getElementById('summaryContainer');
    summaryContainer.classList.remove('active');

    try {
        // Get configured fields
        const configRes = await IndexLibrary.GetRequest({
            endpoint: '/api/Settings/GetSummarizeConfigurations'
        });

        if (!configRes.ok) {
            throw new Error('Failed to fetch summarization configuration');
        }

        const configData = await configRes.json();
        fieldsToFetch = configData.summarizeFields
            ? configData.summarizeFields.split(',').map(f => f.trim())
            : ["System.Id", "System.Title", "System.Description", "System.State"];

        // Get work item
        const workItem = await IndexLibrary.GetWorkItemWithFields(workItemId, fieldsToFetch);

        // Build field dictionary
        const workItemFields = {};
        fieldsToFetch.forEach(field => {
            workItemFields[field] = workItem.fields[field];
        });

        // Force generate new summary
        const generateRes = await IndexLibrary.PostRequest({
            endpoint: '/api/WorkItemSummary/Generate',
            body: {
                organizationId: organizationId,
                devOpsProjectId: projectId,
                devOpsProjectName: projectName,
                workItemId: workItemId,
                workItemFields: workItemFields,
                createdBy: userEmail
            }
        });

        if (!generateRes.ok) {
            const errorData = await generateRes.text();
            throw new Error(errorData || 'Failed to regenerate summary');
        }

        const summaryData = await generateRes.json();
        console.log("Summary regenerated successfully, updated timestamp:", summaryData.lastUpdated);
        displaySummary(summaryData.summary, summaryData.lastUpdated);

    } catch (error) {
        console.error("Error regenerating summary:", error);
        document.getElementById('loadingContainer').innerHTML =
            '<div style="color: red;">Error: ' + error.message + '</div>';
    }
}

function closeDialog() {
    const config = IndexLibrary.SDK.getConfiguration();
    if (config.panel) {
        config.panel.close();
    }
}

// Initialize when ready
console.log("SummarizeDialog: Script loaded, waiting for IndexLibrary...");

// Wait for IndexLibrary to be available
function waitForIndexLibrary() {
    if (typeof IndexLibrary !== 'undefined' && IndexLibrary.InitializeSDK) {
        console.log("SummarizeDialog: IndexLibrary found, initializing...");
        init();
    } else {
        console.log("SummarizeDialog: IndexLibrary not yet available, waiting...");
        setTimeout(waitForIndexLibrary, 100);
    }
}

waitForIndexLibrary();
