const fs = require('fs');
const f = '/app/dist/src/public/public.service.js';
let s = fs.readFileSync(f, 'utf8');
const start = s.indexOf('    groupImagesByColor(variants');
const end = s.indexOf('    async resolveCategoryIcon(category) {');
if (start < 0 || end < 0) {
  console.error('markers not found');
  process.exit(1);
}
const repl = `    groupImagesByColor(variants) {
        const groups = new Map();
        for (const variant of variants) {
            const key = variant.colorId ?? \`variant:\${variant.sdsVariantId}\`;
            let group = groups.get(key);
            if (!group) {
                group = { colorId: variant.colorId, colorName: variant.colorName, colorHex: variant.colorHex, images: [] };
                groups.set(key, group);
            }
            const design = (variant.designData ?? {});
            const urls = [
                variant.imageUrl,
                ...((design.prototypeResultGroups ?? []).map((i) => i?.resultImage)),
                ...((design.detailImgUrls ?? []).map((i) => i?.imageUrl)),
            ];
            for (const url of urls) {
                const value = typeof url === 'string' ? url.trim() : '';
                if (value && !group.images.includes(value)) {
                    group.images.push(value);
                }
            }
        }
        return [...groups.values()];
    }
`;
s = s.slice(0, start) + repl + s.slice(end);
s = s.replace(
  /mediaByColor: this\.groupImagesByColor\(good\.originGood\.variants[^)]*\),/,
  'mediaByColor: this.groupImagesByColor(good.originGood.variants),',
);
fs.writeFileSync(f, s);
console.log('patched OK');
