"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.appendAttachmentPaths = appendAttachmentPaths;
exports.downloadAttachments = downloadAttachments;
exports.normalizeAttachmentUrl = normalizeAttachmentUrl;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const logger_1 = require("../logger");
const INVALID_PATH_CHARS = /[<>:"/\\|?*\x00-\x1f]/g;
function appendAttachmentPaths(text, attachments, heading = 'Local asset files (read/use these if relevant):') {
    if (attachments.length === 0)
        return text;
    const uniquePaths = Array.from(new Set(attachments.map((attachment) => attachment.path)));
    const section = [heading, ...uniquePaths.map((filePath) => `- \`${filePath}\``)].join('\n');
    const trimmed = text.trimEnd();
    return trimmed ? `${trimmed}\n\n${section}` : section;
}
async function downloadAttachments(taskId, attachments, requestInit = {}) {
    if (attachments.length === 0)
        return [];
    const assetDir = path.join(process.cwd(), '.aidev', 'assets', sanitizePathSegment(taskId));
    fs.mkdirSync(assetDir, { recursive: true });
    const usedNames = new Set();
    const downloaded = [];
    for (const attachment of attachments) {
        if (!attachment.url)
            continue;
        const storedName = buildStoredFileName(attachment, usedNames);
        const destination = path.join(assetDir, storedName);
        if (fs.existsSync(destination)) {
            downloaded.push({
                id: attachment.id,
                name: storedName,
                path: toRelativeAssetPath(destination),
                sourceUrl: attachment.url,
            });
            continue;
        }
        try {
            const response = await fetch(attachment.url, {
                ...requestInit,
                redirect: 'follow',
            });
            if (!response.ok) {
                logger_1.logger.warn(`Failed to download attachment "${storedName}" for task ${taskId}: ${response.status} ${response.statusText}`);
                continue;
            }
            const buffer = Buffer.from(await response.arrayBuffer());
            fs.writeFileSync(destination, buffer);
            downloaded.push({
                id: attachment.id,
                name: storedName,
                path: toRelativeAssetPath(destination),
                sourceUrl: attachment.url,
            });
        }
        catch (err) {
            logger_1.logger.warn(`Failed to download attachment "${storedName}" for task ${taskId}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    return downloaded;
}
function normalizeAttachmentUrl(url) {
    try {
        const parsed = new URL(url);
        return `${parsed.origin}${parsed.pathname}`.toLowerCase();
    }
    catch {
        return url.trim().toLowerCase();
    }
}
function buildStoredFileName(attachment, usedNames) {
    const fileName = sanitizeFileName(resolveAttachmentName(attachment));
    const withPrefix = attachment.id
        ? `${sanitizePathSegment(attachment.id)}-${fileName}`
        : fileName;
    let candidate = withPrefix;
    let counter = 2;
    while (usedNames.has(candidate)) {
        const parsed = path.parse(withPrefix);
        candidate = `${parsed.name}-${counter}${parsed.ext}`;
        counter += 1;
    }
    usedNames.add(candidate);
    return candidate;
}
function resolveAttachmentName(attachment) {
    if (attachment.name)
        return attachment.name;
    if (attachment.url) {
        try {
            const parsed = new URL(attachment.url);
            const base = path.posix.basename(parsed.pathname);
            if (base)
                return base;
        }
        catch {
            // Fall through to the default name below.
        }
    }
    return 'attachment';
}
function sanitizeFileName(fileName) {
    const parsed = path.parse(fileName);
    const safeBase = sanitizePathSegment(parsed.name || 'attachment');
    const safeExt = parsed.ext.replace(INVALID_PATH_CHARS, '');
    return `${safeBase}${safeExt}`;
}
function sanitizePathSegment(value) {
    const sanitized = value
        .replace(INVALID_PATH_CHARS, '-')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
    return sanitized || 'attachment';
}
function toRelativeAssetPath(filePath) {
    return path.relative(process.cwd(), filePath).split(path.sep).join('/');
}
//# sourceMappingURL=assets.js.map