"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enrichPinterestSourceContext = exports.selectPrimaryPinterestImage = void 0;
const MAX_PINTEREST_SOURCE_URLS = 1;
const MAX_PINTEREST_PINS = 3;
const MAX_PINTEREST_ARTIFACT_CONTENT_LENGTH = 7_500;
const PINTEREST_HOST_SUFFIX = 'pinterest.com';
const isPinterestUrl = (rawUrl) => {
    try {
        const parsed = new URL(rawUrl);
        const hostname = parsed.hostname.replace(/^www\./, '').toLowerCase();
        return (hostname === PINTEREST_HOST_SUFFIX ||
            hostname.endsWith(`.${PINTEREST_HOST_SUFFIX}`));
    }
    catch {
        return false;
    }
};
const inferImageScore = (url) => {
    const sizePair = url.match(/(?:^|[^\d])(\d{2,5})x(\d{2,5})(?:[^\d]|$)/);
    if (sizePair) {
        return Number(sizePair[1]) * Number(sizePair[2]);
    }
    const pinterestWidth = url.match(/\/(\d{2,5})x\//);
    if (pinterestWidth) {
        return Number(pinterestWidth[1]);
    }
    return null;
};
const selectPrimaryPinterestImage = (imageUrls) => {
    const candidates = imageUrls
        .map((url, index) => ({ url, score: inferImageScore(url), index }))
        .filter((candidate) => candidate.url.length > 0);
    if (candidates.length === 0) {
        return null;
    }
    const scoredCandidates = candidates.filter((candidate) => candidate.score !== null);
    if (scoredCandidates.length > 0) {
        return scoredCandidates.reduce((largest, candidate) => candidate.score > largest.score ? candidate : largest).url;
    }
    return candidates[candidates.length - 1].url;
};
exports.selectPrimaryPinterestImage = selectPrimaryPinterestImage;
const compactLine = (label, value) => (value ? `${label}: ${value}` : null);
const buildPinLines = (pin, index) => {
    const primaryImageUrl = (0, exports.selectPrimaryPinterestImage)(pin.image_urls);
    return [
        `Pin ${index + 1}`,
        compactLine('id', pin.id),
        compactLine('title', pin.title),
        compactLine('description', pin.description),
        compactLine('alt_text', pin.alt_text),
        compactLine('dominant_color', pin.dominant_color),
        compactLine('link', pin.link),
        compactLine('primary_image_url', primaryImageUrl),
        pin.image_urls.length > 0
            ? `image_urls: ${pin.image_urls.join(', ')}`
            : null,
    ].filter((line) => Boolean(line));
};
const buildBoardLines = (board) => {
    if (!board) {
        return [];
    }
    return [
        compactLine('board_title', board.name),
        compactLine('board_description', board.description),
        compactLine('board_privacy', board.privacy),
    ].filter((line) => Boolean(line));
};
const buildPinterestArtifact = (input) => {
    const pins = input.pins.slice(0, MAX_PINTEREST_PINS);
    if (pins.length === 0) {
        return null;
    }
    const label = input.board?.name
        ? `Pinterest: ${input.board.name}`
        : 'Pinterest visual reference';
    const content = [
        `source_url: ${input.sourceUrl}`,
        ...buildBoardLines(input.board),
        ...pins.flatMap((pin, index) => ['', ...buildPinLines(pin, index)]),
    ]
        .join('\n')
        .trim()
        .slice(0, MAX_PINTEREST_ARTIFACT_CONTENT_LENGTH);
    if (!content) {
        return null;
    }
    return {
        kind: 'visualBrief',
        label,
        content,
    };
};
/**
 * Enriches Pinterest source URLs through the existing proxy-backed integration
 * client, preserving local auth/token handling outside MCP.
 */
const enrichPinterestSourceContext = async (input) => {
    const allPinterestUrls = input.sourceUrls.filter(isPinterestUrl);
    const pinterestUrls = allPinterestUrls.slice(0, MAX_PINTEREST_SOURCE_URLS);
    if (!input.integrationsClient || pinterestUrls.length === 0) {
        return { sourceArtifacts: [], warnings: [] };
    }
    const sourceArtifacts = [];
    const warnings = [];
    const skippedPinterestUrlCount = allPinterestUrls.length - pinterestUrls.length;
    if (skippedPinterestUrlCount > 0) {
        warnings.push(`Only the first Pinterest source URL is enriched; ${skippedPinterestUrlCount} additional Pinterest URL(s) remain as plain source links.`);
    }
    for (const sourceUrl of pinterestUrls) {
        const result = await input.integrationsClient.fetchPinterest(sourceUrl);
        if (result.status === 'not_connected') {
            warnings.push('Pinterest is not connected; using the Pinterest URL without authenticated board context.');
            continue;
        }
        if (result.status === 'error') {
            warnings.push(`Pinterest fetch failed; using the Pinterest URL without authenticated board context. ${result.message}`);
            continue;
        }
        const artifact = buildPinterestArtifact({
            sourceUrl,
            board: result.type === 'board' ? result.board : undefined,
            pins: result.pins,
        });
        if (artifact) {
            sourceArtifacts.push(artifact);
        }
    }
    return { sourceArtifacts, warnings };
};
exports.enrichPinterestSourceContext = enrichPinterestSourceContext;
//# sourceMappingURL=pinterestSourceContext.js.map