"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadDocumentSourcesToTemp = downloadDocumentSourcesToTemp;
const fs = __importStar(require("node:fs"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const sanitizeFileName = (name) => {
    const base = path.basename(name || 'document').replace(/[^\w.\- ()[\]]+/g, '_');
    return base.length > 0 ? base : 'document.bin';
};
/**
 * Download HTTP(S) document URLs to a temporary directory for local processing (e.g. Python synthesis).
 * Expects URLs readable by the server (e.g. SAS-enabled blob URLs).
 */
async function downloadDocumentSourcesToTemp(entries) {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trusys-doc-src-'));
    const sources = [];
    const cleanup = () => {
        try {
            if (fs.existsSync(tempDir)) {
                fs.rmSync(tempDir, { recursive: true, force: true });
            }
        }
        catch {
            // best-effort cleanup
        }
    };
    try {
        for (let i = 0; i < entries.length; i++) {
            const { url, name } = entries[i];
            if (!url || typeof url !== 'string') {
                throw new Error(`Invalid document URL at index ${i}`);
            }
            const res = await fetch(decodeURIComponent(url), { redirect: 'follow' });
            if (!res.ok) {
                throw new Error(`Failed to download document (${res.status}): ${url}`);
            }
            const buf = Buffer.from(await res.arrayBuffer());
            const fileName = sanitizeFileName(name || `document-${i}`);
            const localPath = path.join(tempDir, `${i}-${fileName}`);
            fs.writeFileSync(localPath, buf);
            sources.push({ localPath, fileName });
        }
        return { sources, cleanup };
    }
    catch (e) {
        cleanup();
        throw e;
    }
}
//# sourceMappingURL=downloadDocumentSourcesToTemp.js.map