"use strict";
var BrowserAgentAgent;
(function (BrowserAgentAgent) {
    class GoogleSheetsService {
        static async getAuthToken(interactive = false) {
            return new Promise((resolve, reject) => {
                chrome.identity.getAuthToken({ interactive }, (token) => {
                    if (chrome.runtime.lastError) {
                        reject(chrome.runtime.lastError);
                    }
                    else if (token) {
                        resolve(token);
                    }
                    else {
                        reject(new Error("No token returned"));
                    }
                });
            });
        }
        static async authHeaders() {
            const config = await BrowserAgent.getStoredConfig();
            const headers = { "Content-Type": "application/json" };
            if (config.authToken)
                headers["Authorization"] = `Bearer ${config.authToken}`;
            return headers;
        }
        static async getServiceAccountEmail() {
            try {
                const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/service-account`, {
                    method: "POST",
                    headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                    body: "{}"
                });
                if (!response.ok)
                    return { ok: false, error: `Backend returned HTTP ${response.status}.` };
                const data = await response.json();
                if (data.ok === true && typeof data.email === "string")
                    return { ok: true, email: data.email };
                return { ok: false, error: data?.error?.message || "Service account email unavailable." };
            }
            catch (err) {
                const message = err instanceof Error ? err.message : String(err);
                return { ok: false, error: `Could not reach the backend: ${message}` };
            }
        }
        static async checkAccess(spreadsheetId) {
            try {
                const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/check`, {
                    method: "POST",
                    headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                    body: JSON.stringify({ spreadsheetId })
                });
                if (!response.ok)
                    return { ok: false, error: `Backend returned HTTP ${response.status}.` };
                const data = await response.json();
                if (data.ok === true)
                    return { ok: true, title: typeof data.title === "string" ? data.title : undefined };
                return { ok: false, email: data.serviceAccountEmail, error: data?.error?.message };
            }
            catch (err) {
                const message = err instanceof Error ? err.message : String(err);
                console.error("checkAccess error", err);
                return { ok: false, error: `Could not reach the backend: ${message}` };
            }
        }
        static async setupMasterSheet(spreadsheetId, sheetName) {
            try {
                const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/setup`, {
                    method: "POST",
                    headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                    body: JSON.stringify({ spreadsheetId, sheetName })
                });
                return response.ok;
            }
            catch {
                return false;
            }
        }
        static async createRunSheet(spreadsheetId) {
            try {
                const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/run-sheet`, {
                    method: "POST",
                    headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                    body: JSON.stringify({ spreadsheetId })
                });
                if (!response.ok)
                    return null;
                const data = await response.json();
                const sheetTitle = data.sheetTitle || data.sheetName;
                const sheetId = typeof data.sheetId === "number" ? data.sheetId : null;
                if (!sheetTitle)
                    return null;
                if (sheetId === null)
                    return null;
                return { sheetTitle, sheetId };
            }
            catch {
                return null;
            }
        }
        static async getSourceStats(spreadsheetId, sheetName, extractedColumn, searchTermColumn) {
            try {
                const rows = await GoogleSheetsService.readSourceRows(spreadsheetId, sheetName);
                let unparsed = 0;
                for (const row of rows) {
                    const term = String(row[searchTermColumn] ?? "").trim();
                    if (!term)
                        continue;
                    if (BrowserAgentAgent.shouldProcess(row[extractedColumn]))
                        unparsed++;
                }
                return { ok: true, total: rows.length, unparsed };
            }
            catch (err) {
                return { ok: false, error: err instanceof Error ? err.message : String(err) };
            }
        }
        /**
         * Read source rows as header-keyed objects. Each row also carries a
         * synthetic `_rowNumber` (1-based, header counts as row 1) so callers can
         * write back to the same row via updateSourceRow.
         */
        static async readSourceRows(spreadsheetId, sheetName) {
            const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/read`, {
                method: "POST",
                headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                body: JSON.stringify({ spreadsheetId, sheetName })
            });
            if (!response.ok)
                throw new Error(`readSourceRows failed: HTTP ${response.status}`);
            const data = await response.json();
            return data.data || [];
        }
        static async appendResultRows(spreadsheetId, sheetName, rows) {
            if (rows.length === 0)
                return 0;
            const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/write`, {
                method: "POST",
                headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                body: JSON.stringify({ spreadsheetId, sheetName, rows })
            });
            if (!response.ok) {
                const text = await response.text().catch(() => "");
                throw new Error(`appendResultRows failed: HTTP ${response.status} ${text}`);
            }
            const data = await response.json();
            return Number(data.addedCount || 0);
        }
        static async updateSourceRow(spreadsheetId, sheetName, rowNumber, fields) {
            const response = await fetch(`${await BrowserAgent.getBackendBaseUrl()}/v1/sheets/update-source-row`, {
                method: "POST",
                headers: await BrowserAgentAgent.GoogleSheetsService.authHeaders(),
                body: JSON.stringify({ spreadsheetId, sheetName, rowNumber, fields })
            });
            if (!response.ok) {
                const text = await response.text().catch(() => "");
                throw new Error(`updateSourceRow failed: HTTP ${response.status} ${text}`);
            }
        }
    }
    BrowserAgentAgent.GoogleSheetsService = GoogleSheetsService;
})(BrowserAgentAgent || (BrowserAgentAgent = {}));
//# sourceMappingURL=GoogleSheetsService.js.map