Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(instagram): split service into focused modules

spacesdrivec4d37e3234cc
diff --git a/backend/services/analyticsMath.js b/backend/services/analyticsMath.js
new file mode 100644
index 0000000..d825c1f
--- /dev/null
+++ b/backend/services/analyticsMath.js
@@ -0,0 +1,57 @@
+export const DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+export const DAY_MS = 86400000;
+
+export function sumOf(items, pickValue) {
+ return items.reduce((total, item) => total + pickValue(item), 0);
+}
+
+export function roundedAverage(total, count) {
+ return count > 0 ? Math.round(total / count) : 0;
+}
+
+export function medianOf(values) {
+ const sorted = [...values].sort((first, second) => first - second);
+ const middle = Math.floor(sorted.length / 2);
+ if (sorted.length % 2) return sorted[middle];
+ return Math.round((sorted[middle - 1] + sorted[middle]) / 2);
+}
+
+export function countWithinDays(dates, now, days) {
+ return dates.filter(date => (now - date.getTime()) <= days * DAY_MS).length;
+}
+
+export function postFrequency(dates, postCount) {
+ if (dates.length < 2) return { perWeek: 0, perMonth: 0 };
+ const times = dates.map(date => date.getTime());
+ const spanDays = Math.max(1, (Math.max(...times) - Math.min(...times)) / DAY_MS);
+ return {
+ perWeek: parseFloat((postCount / spanDays * 7).toFixed(1)),
+ perMonth: parseFloat((postCount / spanDays * 30).toFixed(1)),
+ };
+}
+
+function coefficientOfVariation(mean, stdDev) {
+ if (mean > 0) return stdDev / mean;
+ return stdDev > 0 ? 10 : 0;
+}
+
+// 100 when every value is equal, lower as values spread out relative to their mean
+export function consistencyScore(values) {
+ if (values.length < 3) return 0;
+ const mean = values.reduce((total, value) => total + value, 0) / values.length;
+ const variance = values.reduce((total, value) => total + Math.pow(value - mean, 2), 0) / values.length;
+ const variation = coefficientOfVariation(mean, Math.sqrt(variance));
+ return Math.max(0, Math.min(100, Math.round(100 / (1 + variation))));
+}
+
+export function bestToAverageRatio(best, average) {
+ return average > 0 ? parseFloat((best / average).toFixed(1)) : 0;
+}
+
+export function pickHighest(items, field) {
+ return items.reduce((best, item) => item[field] > best[field] ? item : best, items[0]);
+}
+
+export function monthKey(date) {
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
+}
diff --git a/backend/services/analyticsMath.test.js b/backend/services/analyticsMath.test.js
new file mode 100644
index 0000000..58cbc19
--- /dev/null
+++ b/backend/services/analyticsMath.test.js
@@ -0,0 +1,66 @@
+process.env.TZ = 'UTC';
+
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ DAY_NAMES, DAY_MS, sumOf, roundedAverage, medianOf, countWithinDays, postFrequency,
+ consistencyScore, bestToAverageRatio, pickHighest, monthKey,
+} from './analyticsMath.js';
+
+const NOW = Date.parse('2026-09-01T12:00:00Z');
+const daysAgo = (days) => new Date(NOW - days * DAY_MS);
+
+describe('analyticsMath', () => {
+ test('day names start on Sunday like Date#getDay', () => {
+ assert.deepStrictEqual(DAY_NAMES, ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']);
+ assert.equal(DAY_MS, 86400000);
+ });
+
+ test('sumOf and roundedAverage', () => {
+ assert.equal(sumOf([{ score: 2 }, { score: 5 }], item => item.score), 7);
+ assert.equal(sumOf([], item => item.score), 0);
+ assert.equal(roundedAverage(7, 2), 4);
+ assert.equal(roundedAverage(7, 0), 0);
+ });
+
+ test('medianOf rounds the middle pair and does not reorder its input', () => {
+ const values = [9, 1, 4];
+ assert.equal(medianOf(values), 4);
+ assert.deepStrictEqual(values, [9, 1, 4]);
+ assert.equal(medianOf([1, 2, 3, 6]), 3);
+ assert.equal(medianOf([1, 2]), 2);
+ });
+
+ test('countWithinDays includes the boundary day', () => {
+ const dates = [daysAgo(0), daysAgo(7), daysAgo(7.5), daysAgo(30)];
+ assert.equal(countWithinDays(dates, NOW, 7), 2);
+ assert.equal(countWithinDays(dates, NOW, 30), 4);
+ });
+
+ test('postFrequency spreads the post count over at least one day', () => {
+ assert.deepStrictEqual(postFrequency([daysAgo(1)], 5), { perWeek: 0, perMonth: 0 });
+ assert.deepStrictEqual(postFrequency([daysAgo(0), daysAgo(14)], 4), { perWeek: 2, perMonth: 8.6 });
+ assert.deepStrictEqual(postFrequency([daysAgo(0), daysAgo(0)], 3), { perWeek: 21, perMonth: 90 });
+ });
+
+ test('consistencyScore needs three values and handles a zero mean', () => {
+ assert.equal(consistencyScore([1, 2]), 0);
+ assert.equal(consistencyScore([5, 5, 5]), 100);
+ assert.equal(consistencyScore([0, 0, 0]), 100);
+ assert.equal(consistencyScore([-1, 0, 1]), 9);
+ assert.equal(consistencyScore([10, 20, 30]), 71);
+ });
+
+ test('bestToAverageRatio and pickHighest keep the first of equal items', () => {
+ assert.equal(bestToAverageRatio(50, 12), 4.2);
+ assert.equal(bestToAverageRatio(50, 0), 0);
+ const items = [{ id: 'a', value: 1 }, { id: 'b', value: 3 }, { id: 'c', value: 3 }];
+ assert.equal(pickHighest(items, 'value').id, 'b');
+ assert.equal(pickHighest([], 'value'), undefined);
+ });
+
+ test('monthKey uses local time', () => {
+ assert.equal(monthKey(new Date('2026-01-31T23:30:00Z')), '2026-01');
+ assert.equal(monthKey(new Date('2025-12-01T00:00:00Z')), '2025-12');
+ });
+});
diff --git a/backend/services/fixtures/fakeFetch.js b/backend/services/fixtures/fakeFetch.js
new file mode 100644
index 0000000..dd703dd
--- /dev/null
+++ b/backend/services/fixtures/fakeFetch.js
@@ -0,0 +1,30 @@
+// replaces global fetch with a scripted responder and records each request
+export function reply(body, status = 200, statusText = 'OK') {
+ return { body, status, statusText };
+}
+
+export function installFetch(respond) {
+ const requests = [];
+ const originalFetch = globalThis.fetch;
+
+ globalThis.fetch = async (url, options = {}) => {
+ const request = { url: String(url), method: options.method ?? 'GET' };
+ if (options.headers) request.headers = options.headers;
+ if (options.body !== undefined) request.body = String(options.body);
+ requests.push(request);
+
+ const outcome = await respond(request, requests.length);
+ if (outcome instanceof Error) throw outcome;
+ return {
+ status: outcome.status,
+ statusText: outcome.statusText,
+ ok: outcome.status >= 200 && outcome.status < 300,
+ json: async () => outcome.body,
+ };
+ };
+
+ return {
+ requests,
+ restore() { globalThis.fetch = originalFetch; },
+ };
+}
diff --git a/backend/services/fixtures/fakeSupabase.js b/backend/services/fixtures/fakeSupabase.js
new file mode 100644
index 0000000..6c72712
--- /dev/null
+++ b/backend/services/fixtures/fakeSupabase.js
@@ -0,0 +1,62 @@
+// in-memory stand-in for the supabase query builder calls made by lib/db.js; records every call
+function copy(value) {
+ return value === undefined ? undefined : structuredClone(value);
+}
+
+function matchesFilters(row, filters) {
+ return filters.every(([column, value]) => row[column] === value);
+}
+
+function queryBuilder(action, run) {
+ const filters = [];
+ const query = {
+ select() { return query; },
+ eq(column, value) {
+ filters.push([column, value]);
+ return query;
+ },
+ single() {
+ const found = run(action, filters);
+ if (found.length === 0) return Promise.resolve({ data: null, error: { message: 'no rows' } });
+ return Promise.resolve({ data: found[0], error: null });
+ },
+ then(resolve, reject) {
+ return Promise.resolve({ data: run(action, filters), error: null }).then(resolve, reject);
+ },
+ };
+ return query;
+}
+
+export function fakeSupabase(rows = []) {
+ const table = rows.map(copy);
+ const calls = [];
+
+ function run(action, filters) {
+ calls.push({ ...copy(action), filters: copy(filters) });
+ const found = table.filter(row => matchesFilters(row, filters));
+ if (action.type === 'update') found.forEach(row => Object.assign(row, copy(action.values)));
+ if (action.type === 'insert') table.push(copy(action.values));
+ if (action.type === 'delete') {
+ found.forEach(row => table.splice(table.indexOf(row), 1));
+ }
+ return found.map(copy);
+ }
+
+ return {
+ calls,
+ table,
+ from(name) {
+ return {
+ select: (columns) => queryBuilder({ type: 'select', table: name, columns }, run),
+ update: (values) => queryBuilder({ type: 'update', table: name, values }, run),
+ insert: (values) => queryBuilder({ type: 'insert', table: name, values }, run),
+ delete: () => queryBuilder({ type: 'delete', table: name }, run),
+ };
+ },
+ };
+}
+
+export function accountRow(account, userId = 'user-1') {
+ const { id, platform, ...data } = account;
+ return { id, platform, user_id: userId, data };
+}
diff --git a/backend/services/fixtures/golden.js b/backend/services/fixtures/golden.js
new file mode 100644
index 0000000..f04b526
--- /dev/null
+++ b/backend/services/fixtures/golden.js
@@ -0,0 +1,25 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+
+// json drops undefined and non-finite numbers, so mark them to keep them visible in the snapshot
+function encodeValue(_key, value) {
+ if (value === undefined) return '[undefined]';
+ if (typeof value === 'number' && !Number.isFinite(value)) return `[${value}]`;
+ return value;
+}
+
+export function snapshot(value) {
+ return JSON.parse(JSON.stringify(value, encodeValue));
+}
+
+export function readGolden(name) {
+ return JSON.parse(readFileSync(new URL(`./${name}.golden.json`, import.meta.url), 'utf8'));
+}
+
+// the string comparison also pins key order, which deepStrictEqual ignores
+export function assertGolden(actual, name) {
+ const expected = readGolden(name);
+ const actualSnapshot = snapshot(actual);
+ assert.deepStrictEqual(actualSnapshot, expected);
+ assert.equal(JSON.stringify(actualSnapshot), JSON.stringify(expected));
+}
diff --git a/backend/services/fixtures/instagramAnalytics.empty.golden.json b/backend/services/fixtures/instagramAnalytics.empty.golden.json
new file mode 100644
index 0000000..99e48cc
--- /dev/null
+++ b/backend/services/fixtures/instagramAnalytics.empty.golden.json
@@ -0,0 +1,154 @@
+{
+ "empty": {
+ "totalPosts": 7,
+ "fetchedPosts": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalEngagement": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "medianLikes": 0,
+ "medianComments": 0,
+ "engagementRate": 0,
+ "likesPerFollower": 0,
+ "commentsPerFollower": 0,
+ "totalViews": 0,
+ "avgViews": 0,
+ "mediaWithViews": 0,
+ "bestByLikes": null,
+ "bestByComments": null,
+ "worstByLikes": null,
+ "recentMedia": [],
+ "contentTypeStats": {
+ "reel": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "post": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "video": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ }
+ },
+ "postFrequency": {
+ "perWeek": 0,
+ "perMonth": 0
+ },
+ "topPosts": [],
+ "hashtagAnalysis": [],
+ "captionLengthCorrelation": [],
+ "postsByDayOfWeek": [],
+ "postsByHour": [],
+ "engagementTimeline": [],
+ "monthlyBreakdown": [],
+ "postsLast7Days": 0,
+ "postsLast30Days": 0,
+ "postsLast90Days": 0,
+ "viralityScore": 0,
+ "consistencyScore": 0,
+ "bestPostingDay": "",
+ "bestPostingHour": "",
+ "likesToCommentsRatio": 0
+ },
+ "missing": {
+ "totalPosts": 0,
+ "fetchedPosts": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalEngagement": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "medianLikes": 0,
+ "medianComments": 0,
+ "engagementRate": 0,
+ "likesPerFollower": 0,
+ "commentsPerFollower": 0,
+ "totalViews": 0,
+ "avgViews": 0,
+ "mediaWithViews": 0,
+ "bestByLikes": null,
+ "bestByComments": null,
+ "worstByLikes": null,
+ "recentMedia": [],
+ "contentTypeStats": {
+ "reel": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "post": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "video": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ }
+ },
+ "postFrequency": {
+ "perWeek": 0,
+ "perMonth": 0
+ },
+ "topPosts": [],
+ "hashtagAnalysis": [],
+ "captionLengthCorrelation": [],
+ "postsByDayOfWeek": [],
+ "postsByHour": [],
+ "engagementTimeline": [],
+ "monthlyBreakdown": [],
+ "postsLast7Days": 0,
+ "postsLast30Days": 0,
+ "postsLast90Days": 0,
+ "viralityScore": 0,
+ "consistencyScore": 0,
+ "bestPostingDay": "",
+ "bestPostingHour": "",
+ "likesToCommentsRatio": 0
+ }
+}
diff --git a/backend/services/fixtures/instagramAnalytics.generated.golden.json b/backend/services/fixtures/instagramAnalytics.generated.golden.json
new file mode 100644
index 0000000..76c3166
--- /dev/null
+++ b/backend/services/fixtures/instagramAnalytics.generated.golden.json
@@ -0,0 +1,921 @@
+{
+ "totalPosts": 24,
+ "fetchedPosts": 24,
+ "totalLikes": 2212,
+ "totalComments": 336,
+ "totalEngagement": 2548,
+ "avgLikes": 92,
+ "avgComments": 14,
+ "avgEngagement": 106,
+ "medianLikes": 89,
+ "medianComments": 14,
+ "engagementRate": 11.8,
+ "likesPerFollower": 10.24,
+ "commentsPerFollower": 1.56,
+ "likesToCommentsRatio": 6.6,
+ "totalViews": 21600,
+ "avgViews": 1200,
+ "mediaWithViews": 18,
+ "bestByLikes": {
+ "id": "g16",
+ "caption": "Post number 16 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g16.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g16/",
+ "timestamp": "2026-07-05T20:00:00+0000",
+ "likeCount": 192,
+ "commentsCount": 26,
+ "viewCount": null
+ },
+ "bestByComments": {
+ "id": "g19",
+ "caption": "Post number 19 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g19.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g19/",
+ "timestamp": "2026-06-25T08:00:00+0000",
+ "likeCount": 103,
+ "commentsCount": 29,
+ "viewCount": 1900
+ },
+ "worstByLikes": {
+ "id": "g00",
+ "caption": "Post number 0 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g00.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g00/",
+ "timestamp": "2026-08-30T20:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ "recentMedia": [
+ {
+ "id": "g00",
+ "caption": "Post number 0 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g00.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g00/",
+ "timestamp": "2026-08-30T20:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "g01",
+ "caption": "Post number 1 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g01/",
+ "timestamp": "2026-08-27T08:00:00+0000",
+ "likeCount": 37,
+ "commentsCount": 11,
+ "viewCount": 100
+ },
+ {
+ "id": "g02",
+ "caption": "Post number 2 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g02/",
+ "timestamp": "2026-08-23T20:00:00+0000",
+ "likeCount": 74,
+ "commentsCount": 22,
+ "viewCount": 200
+ },
+ {
+ "id": "g03",
+ "caption": "Post number 3 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g03/",
+ "timestamp": "2026-08-20T08:00:00+0000",
+ "likeCount": 111,
+ "commentsCount": 3,
+ "viewCount": 300
+ },
+ {
+ "id": "g04",
+ "caption": "Post number 4 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g04.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g04/",
+ "timestamp": "2026-08-16T20:00:00+0000",
+ "likeCount": 148,
+ "commentsCount": 14,
+ "viewCount": null
+ },
+ {
+ "id": "g05",
+ "caption": "Post number 5 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g05.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g05/",
+ "timestamp": "2026-08-13T08:00:00+0000",
+ "likeCount": 185,
+ "commentsCount": 25,
+ "viewCount": 500
+ },
+ {
+ "id": "g06",
+ "caption": "Post number 6 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g06.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g06/",
+ "timestamp": "2026-08-09T20:00:00+0000",
+ "likeCount": 22,
+ "commentsCount": 6,
+ "viewCount": 600
+ },
+ {
+ "id": "g07",
+ "caption": "Post number 7 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g07.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g07/",
+ "timestamp": "2026-08-06T08:00:00+0000",
+ "likeCount": 59,
+ "commentsCount": 17,
+ "viewCount": 700
+ },
+ {
+ "id": "g08",
+ "caption": "Post number 8 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g08.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g08/",
+ "timestamp": "2026-08-02T20:00:00+0000",
+ "likeCount": 96,
+ "commentsCount": 28,
+ "viewCount": null
+ },
+ {
+ "id": "g09",
+ "caption": "Post number 9 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g09.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g09/",
+ "timestamp": "2026-07-30T08:00:00+0000",
+ "likeCount": 133,
+ "commentsCount": 9,
+ "viewCount": 900
+ },
+ {
+ "id": "g10",
+ "caption": "Post number 10 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g10.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g10/",
+ "timestamp": "2026-07-26T20:00:00+0000",
+ "likeCount": 170,
+ "commentsCount": 20,
+ "viewCount": 1000
+ },
+ {
+ "id": "g11",
+ "caption": "Post number 11 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g11.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g11/",
+ "timestamp": "2026-07-23T08:00:00+0000",
+ "likeCount": 7,
+ "commentsCount": 1,
+ "viewCount": 1100
+ },
+ {
+ "id": "g12",
+ "caption": "Post number 12 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g12/",
+ "timestamp": "2026-07-19T20:00:00+0000",
+ "likeCount": 44,
+ "commentsCount": 12,
+ "viewCount": null
+ },
+ {
+ "id": "g13",
+ "caption": "Post number 13 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g13.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g13/",
+ "timestamp": "2026-07-16T08:00:00+0000",
+ "likeCount": 81,
+ "commentsCount": 23,
+ "viewCount": 1300
+ },
+ {
+ "id": "g14",
+ "caption": "Post number 14 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g14.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g14/",
+ "timestamp": "2026-07-12T20:00:00+0000",
+ "likeCount": 118,
+ "commentsCount": 4,
+ "viewCount": 1400
+ },
+ {
+ "id": "g15",
+ "caption": "Post number 15 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g15.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g15/",
+ "timestamp": "2026-07-09T08:00:00+0000",
+ "likeCount": 155,
+ "commentsCount": 15,
+ "viewCount": 1500
+ },
+ {
+ "id": "g16",
+ "caption": "Post number 16 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g16.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g16/",
+ "timestamp": "2026-07-05T20:00:00+0000",
+ "likeCount": 192,
+ "commentsCount": 26,
+ "viewCount": null
+ },
+ {
+ "id": "g17",
+ "caption": "Post number 17 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g17.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g17/",
+ "timestamp": "2026-07-02T08:00:00+0000",
+ "likeCount": 29,
+ "commentsCount": 7,
+ "viewCount": 1700
+ },
+ {
+ "id": "g18",
+ "caption": "Post number 18 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g18.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g18/",
+ "timestamp": "2026-06-28T20:00:00+0000",
+ "likeCount": 66,
+ "commentsCount": 18,
+ "viewCount": 1800
+ },
+ {
+ "id": "g19",
+ "caption": "Post number 19 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g19.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g19/",
+ "timestamp": "2026-06-25T08:00:00+0000",
+ "likeCount": 103,
+ "commentsCount": 29,
+ "viewCount": 1900
+ }
+ ],
+ "contentTypeStats": {
+ "reel": {
+ "count": 8,
+ "totalLikes": 708,
+ "totalComments": 84,
+ "totalViews": 7200,
+ "viewsReported": 6,
+ "avgLikes": 89,
+ "avgComments": 11,
+ "avgEngagement": 99,
+ "avgViews": 1200
+ },
+ "post": {
+ "count": 8,
+ "totalLikes": 804,
+ "totalComments": 142,
+ "totalViews": 7200,
+ "viewsReported": 6,
+ "avgLikes": 101,
+ "avgComments": 18,
+ "avgEngagement": 118,
+ "avgViews": 1200
+ },
+ "video": {
+ "count": 8,
+ "totalLikes": 700,
+ "totalComments": 110,
+ "totalViews": 7200,
+ "viewsReported": 6,
+ "avgLikes": 88,
+ "avgComments": 14,
+ "avgEngagement": 101,
+ "avgViews": 1200
+ }
+ },
+ "postFrequency": {
+ "perWeek": 2.1,
+ "perMonth": 8.9
+ },
+ "topPosts": [
+ {
+ "id": "g16",
+ "caption": "Post number 16 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g16.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g16/",
+ "timestamp": "2026-07-05T20:00:00+0000",
+ "likeCount": 192,
+ "commentsCount": 26,
+ "viewCount": null,
+ "engagement": 218
+ },
+ {
+ "id": "g05",
+ "caption": "Post number 5 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g05.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g05/",
+ "timestamp": "2026-08-13T08:00:00+0000",
+ "likeCount": 185,
+ "commentsCount": 25,
+ "viewCount": 500,
+ "engagement": 210
+ },
+ {
+ "id": "g21",
+ "caption": "Post number 21 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g21.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g21/",
+ "timestamp": "2026-06-18T08:00:00+0000",
+ "likeCount": 177,
+ "commentsCount": 21,
+ "viewCount": 2100,
+ "engagement": 198
+ },
+ {
+ "id": "g10",
+ "caption": "Post number 10 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g10.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g10/",
+ "timestamp": "2026-07-26T20:00:00+0000",
+ "likeCount": 170,
+ "commentsCount": 20,
+ "viewCount": 1000,
+ "engagement": 190
+ },
+ {
+ "id": "g15",
+ "caption": "Post number 15 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g15.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g15/",
+ "timestamp": "2026-07-09T08:00:00+0000",
+ "likeCount": 155,
+ "commentsCount": 15,
+ "viewCount": 1500,
+ "engagement": 170
+ },
+ {
+ "id": "g04",
+ "caption": "Post number 4 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g04.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g04/",
+ "timestamp": "2026-08-16T20:00:00+0000",
+ "likeCount": 148,
+ "commentsCount": 14,
+ "viewCount": null,
+ "engagement": 162
+ },
+ {
+ "id": "g20",
+ "caption": "Post number 20 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g20.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g20/",
+ "timestamp": "2026-06-21T20:00:00+0000",
+ "likeCount": 140,
+ "commentsCount": 10,
+ "viewCount": null,
+ "engagement": 150
+ },
+ {
+ "id": "g09",
+ "caption": "Post number 9 #tag0 #tag3 #tag6 #tag9 #tag12 #tag15 #tag18 #tag21 #tag24",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g09.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g09/",
+ "timestamp": "2026-07-30T08:00:00+0000",
+ "likeCount": 133,
+ "commentsCount": 9,
+ "viewCount": 900,
+ "engagement": 142
+ },
+ {
+ "id": "g19",
+ "caption": "Post number 19 #tag2 #tag5 #tag8 #tag11 #tag14 #tag17 #tag20 #tag23",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/g19.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g19/",
+ "timestamp": "2026-06-25T08:00:00+0000",
+ "likeCount": 103,
+ "commentsCount": 29,
+ "viewCount": 1900,
+ "engagement": 132
+ },
+ {
+ "id": "g08",
+ "caption": "Post number 8 #tag1 #tag4 #tag7 #tag10 #tag13 #tag16 #tag19 #tag22",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/g08.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/g08/",
+ "timestamp": "2026-08-02T20:00:00+0000",
+ "likeCount": 96,
+ "commentsCount": 28,
+ "viewCount": null,
+ "engagement": 124
+ }
+ ],
+ "postsByDayOfWeek": [
+ {
+ "day": "Sunday",
+ "shortDay": "Sun",
+ "posts": 12,
+ "avgLikes": 90,
+ "avgComments": 14,
+ "avgEngagement": 104
+ },
+ {
+ "day": "Monday",
+ "shortDay": "Mon",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Tuesday",
+ "shortDay": "Tue",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Wednesday",
+ "shortDay": "Wed",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Thursday",
+ "shortDay": "Thu",
+ "posts": 12,
+ "avgLikes": 94,
+ "avgComments": 15,
+ "avgEngagement": 109
+ },
+ {
+ "day": "Friday",
+ "shortDay": "Fri",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Saturday",
+ "shortDay": "Sat",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingDay": "Thursday",
+ "postsByHour": [
+ {
+ "hour": 0,
+ "label": "0:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 1,
+ "label": "1:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 2,
+ "label": "2:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 3,
+ "label": "3:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 4,
+ "label": "4:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 5,
+ "label": "5:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 6,
+ "label": "6:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 7,
+ "label": "7:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 8,
+ "label": "8:00",
+ "posts": 12,
+ "avgEngagement": 109
+ },
+ {
+ "hour": 9,
+ "label": "9:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 10,
+ "label": "10:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 11,
+ "label": "11:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 12,
+ "label": "12:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 13,
+ "label": "13:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 14,
+ "label": "14:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 15,
+ "label": "15:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 16,
+ "label": "16:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 17,
+ "label": "17:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 18,
+ "label": "18:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 19,
+ "label": "19:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 20,
+ "label": "20:00",
+ "posts": 12,
+ "avgEngagement": 104
+ },
+ {
+ "hour": 21,
+ "label": "21:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 22,
+ "label": "22:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 23,
+ "label": "23:00",
+ "posts": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingHour": "8:00",
+ "engagementTimeline": [
+ {
+ "month": "2026-06",
+ "posts": 6,
+ "likes": 551,
+ "comments": 93,
+ "avgLikes": 92,
+ "avgComments": 16,
+ "engagement": 644
+ },
+ {
+ "month": "2026-07",
+ "posts": 9,
+ "likes": 929,
+ "comments": 117,
+ "avgLikes": 103,
+ "avgComments": 13,
+ "engagement": 1046
+ },
+ {
+ "month": "2026-08",
+ "posts": 9,
+ "likes": 732,
+ "comments": 126,
+ "avgLikes": 81,
+ "avgComments": 14,
+ "engagement": 858
+ }
+ ],
+ "monthlyBreakdown": [
+ {
+ "month": "2026-06",
+ "posts": 6,
+ "likes": 551,
+ "comments": 93,
+ "avgLikes": 92,
+ "avgComments": 16,
+ "engagement": 644
+ },
+ {
+ "month": "2026-07",
+ "posts": 9,
+ "likes": 929,
+ "comments": 117,
+ "avgLikes": 103,
+ "avgComments": 13,
+ "engagement": 1046
+ },
+ {
+ "month": "2026-08",
+ "posts": 9,
+ "likes": 732,
+ "comments": 126,
+ "avgLikes": 81,
+ "avgComments": 14,
+ "engagement": 858
+ }
+ ],
+ "postsLast7Days": 2,
+ "postsLast30Days": 9,
+ "postsLast90Days": 24,
+ "hashtagAnalysis": [
+ {
+ "tag": "#tag0",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag3",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag6",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag9",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag12",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag15",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag18",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag21",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag24",
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "avgEngagement": 99
+ },
+ {
+ "tag": "#tag2",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag5",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag8",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag11",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag14",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag17",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag20",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag23",
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "avgEngagement": 118
+ },
+ {
+ "tag": "#tag1",
+ "count": 8,
+ "likes": 700,
+ "comments": 110,
+ "avgEngagement": 101
+ },
+ {
+ "tag": "#tag4",
+ "count": 8,
+ "likes": 700,
+ "comments": 110,
+ "avgEngagement": 101
+ },
+ {
+ "tag": "#tag7",
+ "count": 8,
+ "likes": 700,
+ "comments": 110,
+ "avgEngagement": 101
+ }
+ ],
+ "captionLengthCorrelation": [
+ {
+ "label": "Medium (51-150)",
+ "count": 24,
+ "avgLikes": 92,
+ "avgComments": 14,
+ "avgEngagement": 106
+ }
+ ],
+ "viralityScore": 2.1,
+ "consistencyScore": 62
+}
diff --git a/backend/services/fixtures/instagramAnalytics.noFollowers.golden.json b/backend/services/fixtures/instagramAnalytics.noFollowers.golden.json
new file mode 100644
index 0000000..23dfb71
--- /dev/null
+++ b/backend/services/fixtures/instagramAnalytics.noFollowers.golden.json
@@ -0,0 +1,828 @@
+{
+ "totalPosts": 13,
+ "fetchedPosts": 13,
+ "totalLikes": 1255,
+ "totalComments": 171,
+ "totalEngagement": 1426,
+ "avgLikes": 97,
+ "avgComments": 13,
+ "avgEngagement": 110,
+ "medianLikes": 45,
+ "medianComments": 5,
+ "engagementRate": 0,
+ "likesPerFollower": 0,
+ "commentsPerFollower": 0,
+ "likesToCommentsRatio": 7.3,
+ "totalViews": 50800,
+ "avgViews": 7257,
+ "mediaWithViews": 7,
+ "bestByLikes": {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000
+ },
+ "bestByComments": {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000
+ },
+ "worstByLikes": {
+ "id": "m06",
+ "caption": "#quiet",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m06.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m06/",
+ "timestamp": "2026-07-14T06:30:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ "recentMedia": [
+ {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400
+ },
+ {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null
+ },
+ {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800
+ },
+ {
+ "id": "m04",
+ "caption": "Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. #Café #travel #reels",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m04.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m04/",
+ "timestamp": "2026-08-10T21:00:00+0000",
+ "likeCount": 300,
+ "commentsCount": 40,
+ "viewCount": 12000
+ },
+ {
+ "id": "m05",
+ "caption": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx #longform",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m05.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m05/",
+ "timestamp": "not-a-date",
+ "likeCount": 10,
+ "commentsCount": 1,
+ "viewCount": null
+ },
+ {
+ "id": "m06",
+ "caption": "#quiet",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m06.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m06/",
+ "timestamp": "2026-07-14T06:30:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "m07",
+ "caption": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm #reels #Àpropos",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m07.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m07/",
+ "timestamp": "2026-07-02T12:00:00+0000",
+ "likeCount": 88,
+ "commentsCount": 12,
+ "viewCount": 0
+ },
+ {
+ "id": "m08",
+ "caption": "Unknown type",
+ "contentType": "story",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m08.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m08/",
+ "timestamp": "2026-06-20T23:59:00+0000",
+ "likeCount": 15,
+ "commentsCount": 2,
+ "viewCount": 100
+ },
+ {
+ "id": "m09",
+ "caption": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m09.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m09/",
+ "timestamp": "2026-06-03T00:00:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": null
+ },
+ {
+ "id": "m10",
+ "caption": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m10.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m10/",
+ "timestamp": "2026-05-01T15:45:00+0000",
+ "likeCount": 60,
+ "commentsCount": 5,
+ "viewCount": 2500
+ },
+ {
+ "id": "m11",
+ "caption": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m11.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m11/",
+ "timestamp": "2026-03-15T08:00:00+0000",
+ "likeCount": 22,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000
+ },
+ {
+ "id": "m13",
+ "caption": "#travel",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m13.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m13/",
+ "timestamp": "",
+ "likeCount": 5,
+ "commentsCount": 1,
+ "viewCount": null
+ }
+ ],
+ "contentTypeStats": {
+ "reel": {
+ "count": 4,
+ "totalLikes": 1008,
+ "totalComments": 141,
+ "totalViews": 47400,
+ "viewsReported": 4,
+ "avgLikes": 252,
+ "avgComments": 35,
+ "avgEngagement": 287,
+ "avgViews": 11850
+ },
+ "post": {
+ "count": 7,
+ "totalLikes": 142,
+ "totalComments": 16,
+ "totalViews": 100,
+ "viewsReported": 1,
+ "avgLikes": 20,
+ "avgComments": 2,
+ "avgEngagement": 23,
+ "avgViews": 100
+ },
+ "video": {
+ "count": 2,
+ "totalLikes": 105,
+ "totalComments": 14,
+ "totalViews": 3300,
+ "viewsReported": 2,
+ "avgLikes": 53,
+ "avgComments": 7,
+ "avgEngagement": 60,
+ "avgViews": 1650
+ }
+ },
+ "postFrequency": {
+ "perWeek": 0.4,
+ "perMonth": 1.6
+ },
+ "topPosts": [
+ {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000,
+ "engagement": 575
+ },
+ {
+ "id": "m04",
+ "caption": "Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. #Café #travel #reels",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m04.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m04/",
+ "timestamp": "2026-08-10T21:00:00+0000",
+ "likeCount": 300,
+ "commentsCount": 40,
+ "viewCount": 12000,
+ "engagement": 340
+ },
+ {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400,
+ "engagement": 134
+ },
+ {
+ "id": "m07",
+ "caption": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm #reels #Àpropos",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m07.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m07/",
+ "timestamp": "2026-07-02T12:00:00+0000",
+ "likeCount": 88,
+ "commentsCount": 12,
+ "viewCount": 0,
+ "engagement": 100
+ },
+ {
+ "id": "m10",
+ "caption": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m10.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m10/",
+ "timestamp": "2026-05-01T15:45:00+0000",
+ "likeCount": 60,
+ "commentsCount": 5,
+ "viewCount": 2500,
+ "engagement": 65
+ },
+ {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800,
+ "engagement": 54
+ },
+ {
+ "id": "m09",
+ "caption": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m09.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m09/",
+ "timestamp": "2026-06-03T00:00:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": null,
+ "engagement": 54
+ },
+ {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null,
+ "engagement": 48
+ },
+ {
+ "id": "m11",
+ "caption": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m11.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m11/",
+ "timestamp": "2026-03-15T08:00:00+0000",
+ "likeCount": 22,
+ "commentsCount": 0,
+ "viewCount": null,
+ "engagement": 22
+ },
+ {
+ "id": "m08",
+ "caption": "Unknown type",
+ "contentType": "story",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m08.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m08/",
+ "timestamp": "2026-06-20T23:59:00+0000",
+ "likeCount": 15,
+ "commentsCount": 2,
+ "viewCount": 100,
+ "engagement": 17
+ }
+ ],
+ "postsByDayOfWeek": [
+ {
+ "day": "Sunday",
+ "shortDay": "Sun",
+ "posts": 1,
+ "avgLikes": 60,
+ "avgComments": 5,
+ "avgEngagement": 65
+ },
+ {
+ "day": "Monday",
+ "shortDay": "Mon",
+ "posts": 2,
+ "avgLikes": 210,
+ "avgComments": 27,
+ "avgEngagement": 237
+ },
+ {
+ "day": "Tuesday",
+ "shortDay": "Tue",
+ "posts": 2,
+ "avgLikes": 28,
+ "avgComments": 5,
+ "avgEngagement": 33
+ },
+ {
+ "day": "Wednesday",
+ "shortDay": "Wed",
+ "posts": 2,
+ "avgLikes": 19,
+ "avgComments": 1,
+ "avgEngagement": 20
+ },
+ {
+ "day": "Thursday",
+ "shortDay": "Thu",
+ "posts": 1,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Friday",
+ "shortDay": "Fri",
+ "posts": 1,
+ "avgLikes": 45,
+ "avgComments": 9,
+ "avgEngagement": 54
+ },
+ {
+ "day": "Saturday",
+ "shortDay": "Sat",
+ "posts": 2,
+ "avgLikes": 67,
+ "avgComments": 8,
+ "avgEngagement": 74
+ }
+ ],
+ "bestPostingDay": "Monday",
+ "postsByHour": [
+ {
+ "hour": 0,
+ "label": "0:00",
+ "posts": 1,
+ "avgEngagement": 17
+ },
+ {
+ "hour": 1,
+ "label": "1:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 2,
+ "label": "2:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 3,
+ "label": "3:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 4,
+ "label": "4:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 5,
+ "label": "5:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 6,
+ "label": "6:00",
+ "posts": 1,
+ "avgEngagement": 11
+ },
+ {
+ "hour": 7,
+ "label": "7:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 8,
+ "label": "8:00",
+ "posts": 1,
+ "avgEngagement": 65
+ },
+ {
+ "hour": 9,
+ "label": "9:00",
+ "posts": 2,
+ "avgEngagement": 94
+ },
+ {
+ "hour": 10,
+ "label": "10:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 11,
+ "label": "11:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 12,
+ "label": "12:00",
+ "posts": 1,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 13,
+ "label": "13:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 14,
+ "label": "14:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 15,
+ "label": "15:00",
+ "posts": 1,
+ "avgEngagement": 54
+ },
+ {
+ "hour": 16,
+ "label": "16:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 17,
+ "label": "17:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 18,
+ "label": "18:00",
+ "posts": 1,
+ "avgEngagement": 48
+ },
+ {
+ "hour": 19,
+ "label": "19:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 20,
+ "label": "20:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 21,
+ "label": "21:00",
+ "posts": 1,
+ "avgEngagement": 340
+ },
+ {
+ "hour": 22,
+ "label": "22:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 23,
+ "label": "23:00",
+ "posts": 2,
+ "avgEngagement": 61
+ }
+ ],
+ "bestPostingHour": "21:00",
+ "engagementTimeline": [
+ {
+ "month": "2025-12",
+ "posts": 1,
+ "likes": 500,
+ "comments": 75,
+ "avgLikes": 500,
+ "avgComments": 75,
+ "engagement": 575
+ },
+ {
+ "month": "2026-03",
+ "posts": 1,
+ "likes": 22,
+ "comments": 0,
+ "avgLikes": 22,
+ "avgComments": 0,
+ "engagement": 22
+ },
+ {
+ "month": "2026-05",
+ "posts": 1,
+ "likes": 60,
+ "comments": 5,
+ "avgLikes": 60,
+ "avgComments": 5,
+ "engagement": 65
+ },
+ {
+ "month": "2026-06",
+ "posts": 2,
+ "likes": 60,
+ "comments": 11,
+ "avgLikes": 30,
+ "avgComments": 6,
+ "engagement": 71
+ },
+ {
+ "month": "2026-07",
+ "posts": 2,
+ "likes": 88,
+ "comments": 12,
+ "avgLikes": 44,
+ "avgComments": 6,
+ "engagement": 100
+ },
+ {
+ "month": "2026-08",
+ "posts": 4,
+ "likes": 510,
+ "comments": 66,
+ "avgLikes": 128,
+ "avgComments": 17,
+ "engagement": 576
+ }
+ ],
+ "monthlyBreakdown": [
+ {
+ "month": "2025-12",
+ "posts": 1,
+ "likes": 500,
+ "comments": 75,
+ "avgLikes": 500,
+ "avgComments": 75,
+ "engagement": 575
+ },
+ {
+ "month": "2026-03",
+ "posts": 1,
+ "likes": 22,
+ "comments": 0,
+ "avgLikes": 22,
+ "avgComments": 0,
+ "engagement": 22
+ },
+ {
+ "month": "2026-05",
+ "posts": 1,
+ "likes": 60,
+ "comments": 5,
+ "avgLikes": 60,
+ "avgComments": 5,
+ "engagement": 65
+ },
+ {
+ "month": "2026-06",
+ "posts": 2,
+ "likes": 60,
+ "comments": 11,
+ "avgLikes": 30,
+ "avgComments": 6,
+ "engagement": 71
+ },
+ {
+ "month": "2026-07",
+ "posts": 2,
+ "likes": 88,
+ "comments": 12,
+ "avgLikes": 44,
+ "avgComments": 6,
+ "engagement": 100
+ },
+ {
+ "month": "2026-08",
+ "posts": 4,
+ "likes": 510,
+ "comments": 66,
+ "avgLikes": 128,
+ "avgComments": 17,
+ "engagement": 576
+ }
+ ],
+ "postsLast7Days": 2,
+ "postsLast30Days": 4,
+ "postsLast90Days": 7,
+ "hashtagAnalysis": [
+ {
+ "tag": "#travel",
+ "count": 6,
+ "likes": 1470,
+ "comments": 214,
+ "avgEngagement": 281
+ },
+ {
+ "tag": "#reels",
+ "count": 2,
+ "likes": 388,
+ "comments": 52,
+ "avgEngagement": 220
+ },
+ {
+ "tag": "#sunset",
+ "count": 1,
+ "likes": 120,
+ "comments": 14,
+ "avgEngagement": 134
+ },
+ {
+ "tag": "#café",
+ "count": 1,
+ "likes": 300,
+ "comments": 40,
+ "avgEngagement": 340
+ },
+ {
+ "tag": "#longform",
+ "count": 1,
+ "likes": 10,
+ "comments": 1,
+ "avgEngagement": 11
+ },
+ {
+ "tag": "#quiet",
+ "count": 1,
+ "likes": 0,
+ "comments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "tag": "#àpropos",
+ "count": 1,
+ "likes": 88,
+ "comments": 12,
+ "avgEngagement": 100
+ },
+ {
+ "tag": "#newyear",
+ "count": 1,
+ "likes": 500,
+ "comments": 75,
+ "avgEngagement": 575
+ }
+ ],
+ "captionLengthCorrelation": [
+ {
+ "label": "No caption",
+ "count": 1,
+ "avgLikes": 45,
+ "avgComments": 3,
+ "avgEngagement": 48
+ },
+ {
+ "label": "Short (1-50)",
+ "count": 7,
+ "avgLikes": 104,
+ "avgComments": 16,
+ "avgEngagement": 120
+ },
+ {
+ "label": "Medium (51-150)",
+ "count": 1,
+ "avgLikes": 88,
+ "avgComments": 12,
+ "avgEngagement": 100
+ },
+ {
+ "label": "Long (151-300)",
+ "count": 3,
+ "avgLikes": 127,
+ "avgComments": 15,
+ "avgEngagement": 142
+ },
+ {
+ "label": "Very Long (300+)",
+ "count": 1,
+ "avgLikes": 10,
+ "avgComments": 1,
+ "avgEngagement": 11
+ }
+ ],
+ "viralityScore": 5.2,
+ "consistencyScore": 41
+}
diff --git a/backend/services/fixtures/instagramAnalytics.rich.golden.json b/backend/services/fixtures/instagramAnalytics.rich.golden.json
new file mode 100644
index 0000000..ed7c9dc
--- /dev/null
+++ b/backend/services/fixtures/instagramAnalytics.rich.golden.json
@@ -0,0 +1,828 @@
+{
+ "totalPosts": 140,
+ "fetchedPosts": 13,
+ "totalLikes": 1255,
+ "totalComments": 171,
+ "totalEngagement": 1426,
+ "avgLikes": 97,
+ "avgComments": 13,
+ "avgEngagement": 110,
+ "medianLikes": 45,
+ "medianComments": 5,
+ "engagementRate": 4.39,
+ "likesPerFollower": 3.86,
+ "commentsPerFollower": 0.53,
+ "likesToCommentsRatio": 7.3,
+ "totalViews": 50800,
+ "avgViews": 7257,
+ "mediaWithViews": 7,
+ "bestByLikes": {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000
+ },
+ "bestByComments": {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000
+ },
+ "worstByLikes": {
+ "id": "m06",
+ "caption": "#quiet",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m06.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m06/",
+ "timestamp": "2026-07-14T06:30:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ "recentMedia": [
+ {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400
+ },
+ {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null
+ },
+ {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800
+ },
+ {
+ "id": "m04",
+ "caption": "Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. #Café #travel #reels",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m04.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m04/",
+ "timestamp": "2026-08-10T21:00:00+0000",
+ "likeCount": 300,
+ "commentsCount": 40,
+ "viewCount": 12000
+ },
+ {
+ "id": "m05",
+ "caption": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx #longform",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m05.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m05/",
+ "timestamp": "not-a-date",
+ "likeCount": 10,
+ "commentsCount": 1,
+ "viewCount": null
+ },
+ {
+ "id": "m06",
+ "caption": "#quiet",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m06.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m06/",
+ "timestamp": "2026-07-14T06:30:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "m07",
+ "caption": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm #reels #Àpropos",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m07.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m07/",
+ "timestamp": "2026-07-02T12:00:00+0000",
+ "likeCount": 88,
+ "commentsCount": 12,
+ "viewCount": 0
+ },
+ {
+ "id": "m08",
+ "caption": "Unknown type",
+ "contentType": "story",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m08.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m08/",
+ "timestamp": "2026-06-20T23:59:00+0000",
+ "likeCount": 15,
+ "commentsCount": 2,
+ "viewCount": 100
+ },
+ {
+ "id": "m09",
+ "caption": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m09.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m09/",
+ "timestamp": "2026-06-03T00:00:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": null
+ },
+ {
+ "id": "m10",
+ "caption": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m10.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m10/",
+ "timestamp": "2026-05-01T15:45:00+0000",
+ "likeCount": 60,
+ "commentsCount": 5,
+ "viewCount": 2500
+ },
+ {
+ "id": "m11",
+ "caption": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m11.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m11/",
+ "timestamp": "2026-03-15T08:00:00+0000",
+ "likeCount": 22,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000
+ },
+ {
+ "id": "m13",
+ "caption": "#travel",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m13.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m13/",
+ "timestamp": "",
+ "likeCount": 5,
+ "commentsCount": 1,
+ "viewCount": null
+ }
+ ],
+ "contentTypeStats": {
+ "reel": {
+ "count": 4,
+ "totalLikes": 1008,
+ "totalComments": 141,
+ "totalViews": 47400,
+ "viewsReported": 4,
+ "avgLikes": 252,
+ "avgComments": 35,
+ "avgEngagement": 287,
+ "avgViews": 11850
+ },
+ "post": {
+ "count": 7,
+ "totalLikes": 142,
+ "totalComments": 16,
+ "totalViews": 100,
+ "viewsReported": 1,
+ "avgLikes": 20,
+ "avgComments": 2,
+ "avgEngagement": 23,
+ "avgViews": 100
+ },
+ "video": {
+ "count": 2,
+ "totalLikes": 105,
+ "totalComments": 14,
+ "totalViews": 3300,
+ "viewsReported": 2,
+ "avgLikes": 53,
+ "avgComments": 7,
+ "avgEngagement": 60,
+ "avgViews": 1650
+ }
+ },
+ "postFrequency": {
+ "perWeek": 0.4,
+ "perMonth": 1.6
+ },
+ "topPosts": [
+ {
+ "id": "m12",
+ "caption": "#Travel #TRAVEL #newyear",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m12.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m12/",
+ "timestamp": "2025-12-31T23:30:00+0000",
+ "likeCount": 500,
+ "commentsCount": 75,
+ "viewCount": 30000,
+ "engagement": 575
+ },
+ {
+ "id": "m04",
+ "caption": "Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. Behind the scenes of the shoot. #Café #travel #reels",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m04.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m04/",
+ "timestamp": "2026-08-10T21:00:00+0000",
+ "likeCount": 300,
+ "commentsCount": 40,
+ "viewCount": 12000,
+ "engagement": 340
+ },
+ {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400,
+ "engagement": 134
+ },
+ {
+ "id": "m07",
+ "caption": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm #reels #Àpropos",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m07.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m07/",
+ "timestamp": "2026-07-02T12:00:00+0000",
+ "likeCount": 88,
+ "commentsCount": 12,
+ "viewCount": 0,
+ "engagement": 100
+ },
+ {
+ "id": "m10",
+ "caption": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m10.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m10/",
+ "timestamp": "2026-05-01T15:45:00+0000",
+ "likeCount": 60,
+ "commentsCount": 5,
+ "viewCount": 2500,
+ "engagement": 65
+ },
+ {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800,
+ "engagement": 54
+ },
+ {
+ "id": "m09",
+ "caption": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m09.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m09/",
+ "timestamp": "2026-06-03T00:00:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": null,
+ "engagement": 54
+ },
+ {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null,
+ "engagement": 48
+ },
+ {
+ "id": "m11",
+ "caption": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m11.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m11/",
+ "timestamp": "2026-03-15T08:00:00+0000",
+ "likeCount": 22,
+ "commentsCount": 0,
+ "viewCount": null,
+ "engagement": 22
+ },
+ {
+ "id": "m08",
+ "caption": "Unknown type",
+ "contentType": "story",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m08.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m08/",
+ "timestamp": "2026-06-20T23:59:00+0000",
+ "likeCount": 15,
+ "commentsCount": 2,
+ "viewCount": 100,
+ "engagement": 17
+ }
+ ],
+ "postsByDayOfWeek": [
+ {
+ "day": "Sunday",
+ "shortDay": "Sun",
+ "posts": 1,
+ "avgLikes": 60,
+ "avgComments": 5,
+ "avgEngagement": 65
+ },
+ {
+ "day": "Monday",
+ "shortDay": "Mon",
+ "posts": 2,
+ "avgLikes": 210,
+ "avgComments": 27,
+ "avgEngagement": 237
+ },
+ {
+ "day": "Tuesday",
+ "shortDay": "Tue",
+ "posts": 2,
+ "avgLikes": 28,
+ "avgComments": 5,
+ "avgEngagement": 33
+ },
+ {
+ "day": "Wednesday",
+ "shortDay": "Wed",
+ "posts": 2,
+ "avgLikes": 19,
+ "avgComments": 1,
+ "avgEngagement": 20
+ },
+ {
+ "day": "Thursday",
+ "shortDay": "Thu",
+ "posts": 1,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Friday",
+ "shortDay": "Fri",
+ "posts": 1,
+ "avgLikes": 45,
+ "avgComments": 9,
+ "avgEngagement": 54
+ },
+ {
+ "day": "Saturday",
+ "shortDay": "Sat",
+ "posts": 2,
+ "avgLikes": 67,
+ "avgComments": 8,
+ "avgEngagement": 74
+ }
+ ],
+ "bestPostingDay": "Monday",
+ "postsByHour": [
+ {
+ "hour": 0,
+ "label": "0:00",
+ "posts": 1,
+ "avgEngagement": 17
+ },
+ {
+ "hour": 1,
+ "label": "1:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 2,
+ "label": "2:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 3,
+ "label": "3:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 4,
+ "label": "4:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 5,
+ "label": "5:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 6,
+ "label": "6:00",
+ "posts": 1,
+ "avgEngagement": 11
+ },
+ {
+ "hour": 7,
+ "label": "7:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 8,
+ "label": "8:00",
+ "posts": 1,
+ "avgEngagement": 65
+ },
+ {
+ "hour": 9,
+ "label": "9:00",
+ "posts": 2,
+ "avgEngagement": 94
+ },
+ {
+ "hour": 10,
+ "label": "10:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 11,
+ "label": "11:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 12,
+ "label": "12:00",
+ "posts": 1,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 13,
+ "label": "13:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 14,
+ "label": "14:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 15,
+ "label": "15:00",
+ "posts": 1,
+ "avgEngagement": 54
+ },
+ {
+ "hour": 16,
+ "label": "16:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 17,
+ "label": "17:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 18,
+ "label": "18:00",
+ "posts": 1,
+ "avgEngagement": 48
+ },
+ {
+ "hour": 19,
+ "label": "19:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 20,
+ "label": "20:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 21,
+ "label": "21:00",
+ "posts": 1,
+ "avgEngagement": 340
+ },
+ {
+ "hour": 22,
+ "label": "22:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 23,
+ "label": "23:00",
+ "posts": 2,
+ "avgEngagement": 61
+ }
+ ],
+ "bestPostingHour": "21:00",
+ "engagementTimeline": [
+ {
+ "month": "2025-12",
+ "posts": 1,
+ "likes": 500,
+ "comments": 75,
+ "avgLikes": 500,
+ "avgComments": 75,
+ "engagement": 575
+ },
+ {
+ "month": "2026-03",
+ "posts": 1,
+ "likes": 22,
+ "comments": 0,
+ "avgLikes": 22,
+ "avgComments": 0,
+ "engagement": 22
+ },
+ {
+ "month": "2026-05",
+ "posts": 1,
+ "likes": 60,
+ "comments": 5,
+ "avgLikes": 60,
+ "avgComments": 5,
+ "engagement": 65
+ },
+ {
+ "month": "2026-06",
+ "posts": 2,
+ "likes": 60,
+ "comments": 11,
+ "avgLikes": 30,
+ "avgComments": 6,
+ "engagement": 71
+ },
+ {
+ "month": "2026-07",
+ "posts": 2,
+ "likes": 88,
+ "comments": 12,
+ "avgLikes": 44,
+ "avgComments": 6,
+ "engagement": 100
+ },
+ {
+ "month": "2026-08",
+ "posts": 4,
+ "likes": 510,
+ "comments": 66,
+ "avgLikes": 128,
+ "avgComments": 17,
+ "engagement": 576
+ }
+ ],
+ "monthlyBreakdown": [
+ {
+ "month": "2025-12",
+ "posts": 1,
+ "likes": 500,
+ "comments": 75,
+ "avgLikes": 500,
+ "avgComments": 75,
+ "engagement": 575
+ },
+ {
+ "month": "2026-03",
+ "posts": 1,
+ "likes": 22,
+ "comments": 0,
+ "avgLikes": 22,
+ "avgComments": 0,
+ "engagement": 22
+ },
+ {
+ "month": "2026-05",
+ "posts": 1,
+ "likes": 60,
+ "comments": 5,
+ "avgLikes": 60,
+ "avgComments": 5,
+ "engagement": 65
+ },
+ {
+ "month": "2026-06",
+ "posts": 2,
+ "likes": 60,
+ "comments": 11,
+ "avgLikes": 30,
+ "avgComments": 6,
+ "engagement": 71
+ },
+ {
+ "month": "2026-07",
+ "posts": 2,
+ "likes": 88,
+ "comments": 12,
+ "avgLikes": 44,
+ "avgComments": 6,
+ "engagement": 100
+ },
+ {
+ "month": "2026-08",
+ "posts": 4,
+ "likes": 510,
+ "comments": 66,
+ "avgLikes": 128,
+ "avgComments": 17,
+ "engagement": 576
+ }
+ ],
+ "postsLast7Days": 2,
+ "postsLast30Days": 4,
+ "postsLast90Days": 7,
+ "hashtagAnalysis": [
+ {
+ "tag": "#travel",
+ "count": 6,
+ "likes": 1470,
+ "comments": 214,
+ "avgEngagement": 281
+ },
+ {
+ "tag": "#reels",
+ "count": 2,
+ "likes": 388,
+ "comments": 52,
+ "avgEngagement": 220
+ },
+ {
+ "tag": "#sunset",
+ "count": 1,
+ "likes": 120,
+ "comments": 14,
+ "avgEngagement": 134
+ },
+ {
+ "tag": "#café",
+ "count": 1,
+ "likes": 300,
+ "comments": 40,
+ "avgEngagement": 340
+ },
+ {
+ "tag": "#longform",
+ "count": 1,
+ "likes": 10,
+ "comments": 1,
+ "avgEngagement": 11
+ },
+ {
+ "tag": "#quiet",
+ "count": 1,
+ "likes": 0,
+ "comments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "tag": "#àpropos",
+ "count": 1,
+ "likes": 88,
+ "comments": 12,
+ "avgEngagement": 100
+ },
+ {
+ "tag": "#newyear",
+ "count": 1,
+ "likes": 500,
+ "comments": 75,
+ "avgEngagement": 575
+ }
+ ],
+ "captionLengthCorrelation": [
+ {
+ "label": "No caption",
+ "count": 1,
+ "avgLikes": 45,
+ "avgComments": 3,
+ "avgEngagement": 48
+ },
+ {
+ "label": "Short (1-50)",
+ "count": 7,
+ "avgLikes": 104,
+ "avgComments": 16,
+ "avgEngagement": 120
+ },
+ {
+ "label": "Medium (51-150)",
+ "count": 1,
+ "avgLikes": 88,
+ "avgComments": 12,
+ "avgEngagement": 100
+ },
+ {
+ "label": "Long (151-300)",
+ "count": 3,
+ "avgLikes": 127,
+ "avgComments": 15,
+ "avgEngagement": 142
+ },
+ {
+ "label": "Very Long (300+)",
+ "count": 1,
+ "avgLikes": 10,
+ "avgComments": 1,
+ "avgEngagement": 11
+ }
+ ],
+ "viralityScore": 5.2,
+ "consistencyScore": 41
+}
diff --git a/backend/services/fixtures/instagramAnalytics.small.golden.json b/backend/services/fixtures/instagramAnalytics.small.golden.json
new file mode 100644
index 0000000..b0a14f8
--- /dev/null
+++ b/backend/services/fixtures/instagramAnalytics.small.golden.json
@@ -0,0 +1,801 @@
+{
+ "single": {
+ "totalPosts": 1,
+ "fetchedPosts": 1,
+ "totalLikes": 120,
+ "totalComments": 14,
+ "totalEngagement": 134,
+ "avgLikes": 120,
+ "avgComments": 14,
+ "avgEngagement": 134,
+ "medianLikes": 120,
+ "medianComments": 14,
+ "engagementRate": 1340,
+ "likesPerFollower": 1200,
+ "commentsPerFollower": 140,
+ "likesToCommentsRatio": 8.6,
+ "totalViews": 5400,
+ "avgViews": 5400,
+ "mediaWithViews": 1,
+ "bestByLikes": {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400
+ },
+ "bestByComments": {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400
+ },
+ "worstByLikes": {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400
+ },
+ "recentMedia": [
+ {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400
+ }
+ ],
+ "contentTypeStats": {
+ "reel": {
+ "count": 1,
+ "totalLikes": 120,
+ "totalComments": 14,
+ "totalViews": 5400,
+ "viewsReported": 1,
+ "avgLikes": 120,
+ "avgComments": 14,
+ "avgEngagement": 134,
+ "avgViews": 5400
+ },
+ "post": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "video": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ }
+ },
+ "postFrequency": {
+ "perWeek": 0,
+ "perMonth": 0
+ },
+ "topPosts": [
+ {
+ "id": "m01",
+ "caption": "#Travel #sunset golden hour over the bay",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m01.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m01/",
+ "timestamp": "2026-08-31T09:15:00+0000",
+ "likeCount": 120,
+ "commentsCount": 14,
+ "viewCount": 5400,
+ "engagement": 134
+ }
+ ],
+ "postsByDayOfWeek": [
+ {
+ "day": "Sunday",
+ "shortDay": "Sun",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Monday",
+ "shortDay": "Mon",
+ "posts": 1,
+ "avgLikes": 120,
+ "avgComments": 14,
+ "avgEngagement": 134
+ },
+ {
+ "day": "Tuesday",
+ "shortDay": "Tue",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Wednesday",
+ "shortDay": "Wed",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Thursday",
+ "shortDay": "Thu",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Friday",
+ "shortDay": "Fri",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Saturday",
+ "shortDay": "Sat",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingDay": "Monday",
+ "postsByHour": [
+ {
+ "hour": 0,
+ "label": "0:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 1,
+ "label": "1:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 2,
+ "label": "2:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 3,
+ "label": "3:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 4,
+ "label": "4:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 5,
+ "label": "5:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 6,
+ "label": "6:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 7,
+ "label": "7:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 8,
+ "label": "8:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 9,
+ "label": "9:00",
+ "posts": 1,
+ "avgEngagement": 134
+ },
+ {
+ "hour": 10,
+ "label": "10:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 11,
+ "label": "11:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 12,
+ "label": "12:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 13,
+ "label": "13:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 14,
+ "label": "14:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 15,
+ "label": "15:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 16,
+ "label": "16:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 17,
+ "label": "17:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 18,
+ "label": "18:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 19,
+ "label": "19:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 20,
+ "label": "20:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 21,
+ "label": "21:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 22,
+ "label": "22:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 23,
+ "label": "23:00",
+ "posts": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingHour": "9:00",
+ "engagementTimeline": [
+ {
+ "month": "2026-08",
+ "posts": 1,
+ "likes": 120,
+ "comments": 14,
+ "avgLikes": 120,
+ "avgComments": 14,
+ "engagement": 134
+ }
+ ],
+ "monthlyBreakdown": [
+ {
+ "month": "2026-08",
+ "posts": 1,
+ "likes": 120,
+ "comments": 14,
+ "avgLikes": 120,
+ "avgComments": 14,
+ "engagement": 134
+ }
+ ],
+ "postsLast7Days": 1,
+ "postsLast30Days": 1,
+ "postsLast90Days": 1,
+ "hashtagAnalysis": [
+ {
+ "tag": "#travel",
+ "count": 1,
+ "likes": 120,
+ "comments": 14,
+ "avgEngagement": 134
+ },
+ {
+ "tag": "#sunset",
+ "count": 1,
+ "likes": 120,
+ "comments": 14,
+ "avgEngagement": 134
+ }
+ ],
+ "captionLengthCorrelation": [
+ {
+ "label": "Short (1-50)",
+ "count": 1,
+ "avgLikes": 120,
+ "avgComments": 14,
+ "avgEngagement": 134
+ }
+ ],
+ "viralityScore": 1,
+ "consistencyScore": 0
+ },
+ "pair": {
+ "totalPosts": 2,
+ "fetchedPosts": 2,
+ "totalLikes": 90,
+ "totalComments": 12,
+ "totalEngagement": 102,
+ "avgLikes": 45,
+ "avgComments": 6,
+ "avgEngagement": 51,
+ "medianLikes": 45,
+ "medianComments": 6,
+ "engagementRate": 510,
+ "likesPerFollower": 450,
+ "commentsPerFollower": 60,
+ "likesToCommentsRatio": 7.5,
+ "totalViews": 800,
+ "avgViews": 800,
+ "mediaWithViews": 1,
+ "bestByLikes": {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null
+ },
+ "bestByComments": {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800
+ },
+ "worstByLikes": {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800
+ },
+ "recentMedia": [
+ {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null
+ },
+ {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800
+ }
+ ],
+ "contentTypeStats": {
+ "reel": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "post": {
+ "count": 1,
+ "totalLikes": 45,
+ "totalComments": 3,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 45,
+ "avgComments": 3,
+ "avgEngagement": 48,
+ "avgViews": 0
+ },
+ "video": {
+ "count": 1,
+ "totalLikes": 45,
+ "totalComments": 9,
+ "totalViews": 800,
+ "viewsReported": 1,
+ "avgLikes": 45,
+ "avgComments": 9,
+ "avgEngagement": 54,
+ "avgViews": 800
+ }
+ },
+ "postFrequency": {
+ "perWeek": 3.2,
+ "perMonth": 13.6
+ },
+ "topPosts": [
+ {
+ "id": "m03",
+ "caption": "Short clip #travel",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/m03.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m03/",
+ "timestamp": "2026-08-25T09:05:00+0000",
+ "likeCount": 45,
+ "commentsCount": 9,
+ "viewCount": 800,
+ "engagement": 54
+ },
+ {
+ "id": "m02",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/m02.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/m02/",
+ "timestamp": "2026-08-29T18:40:00+0000",
+ "likeCount": 45,
+ "commentsCount": 3,
+ "viewCount": null,
+ "engagement": 48
+ }
+ ],
+ "postsByDayOfWeek": [
+ {
+ "day": "Sunday",
+ "shortDay": "Sun",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Monday",
+ "shortDay": "Mon",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Tuesday",
+ "shortDay": "Tue",
+ "posts": 1,
+ "avgLikes": 45,
+ "avgComments": 9,
+ "avgEngagement": 54
+ },
+ {
+ "day": "Wednesday",
+ "shortDay": "Wed",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Thursday",
+ "shortDay": "Thu",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Friday",
+ "shortDay": "Fri",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Saturday",
+ "shortDay": "Sat",
+ "posts": 1,
+ "avgLikes": 45,
+ "avgComments": 3,
+ "avgEngagement": 48
+ }
+ ],
+ "bestPostingDay": "Tuesday",
+ "postsByHour": [
+ {
+ "hour": 0,
+ "label": "0:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 1,
+ "label": "1:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 2,
+ "label": "2:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 3,
+ "label": "3:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 4,
+ "label": "4:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 5,
+ "label": "5:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 6,
+ "label": "6:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 7,
+ "label": "7:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 8,
+ "label": "8:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 9,
+ "label": "9:00",
+ "posts": 1,
+ "avgEngagement": 54
+ },
+ {
+ "hour": 10,
+ "label": "10:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 11,
+ "label": "11:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 12,
+ "label": "12:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 13,
+ "label": "13:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 14,
+ "label": "14:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 15,
+ "label": "15:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 16,
+ "label": "16:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 17,
+ "label": "17:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 18,
+ "label": "18:00",
+ "posts": 1,
+ "avgEngagement": 48
+ },
+ {
+ "hour": 19,
+ "label": "19:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 20,
+ "label": "20:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 21,
+ "label": "21:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 22,
+ "label": "22:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 23,
+ "label": "23:00",
+ "posts": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingHour": "9:00",
+ "engagementTimeline": [
+ {
+ "month": "2026-08",
+ "posts": 2,
+ "likes": 90,
+ "comments": 12,
+ "avgLikes": 45,
+ "avgComments": 6,
+ "engagement": 102
+ }
+ ],
+ "monthlyBreakdown": [
+ {
+ "month": "2026-08",
+ "posts": 2,
+ "likes": 90,
+ "comments": 12,
+ "avgLikes": 45,
+ "avgComments": 6,
+ "engagement": 102
+ }
+ ],
+ "postsLast7Days": 1,
+ "postsLast30Days": 2,
+ "postsLast90Days": 2,
+ "hashtagAnalysis": [
+ {
+ "tag": "#travel",
+ "count": 1,
+ "likes": 45,
+ "comments": 9,
+ "avgEngagement": 54
+ }
+ ],
+ "captionLengthCorrelation": [
+ {
+ "label": "No caption",
+ "count": 1,
+ "avgLikes": 45,
+ "avgComments": 3,
+ "avgEngagement": 48
+ },
+ {
+ "label": "Short (1-50)",
+ "count": 1,
+ "avgLikes": 45,
+ "avgComments": 9,
+ "avgEngagement": 54
+ }
+ ],
+ "viralityScore": 1.1,
+ "consistencyScore": 0
+ }
+}
diff --git a/backend/services/fixtures/instagramAnalytics.zero.golden.json b/backend/services/fixtures/instagramAnalytics.zero.golden.json
new file mode 100644
index 0000000..69c9f3a
--- /dev/null
+++ b/backend/services/fixtures/instagramAnalytics.zero.golden.json
@@ -0,0 +1,425 @@
+{
+ "totalPosts": 3,
+ "fetchedPosts": 3,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalEngagement": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "medianLikes": 0,
+ "medianComments": 0,
+ "engagementRate": 0,
+ "likesPerFollower": 0,
+ "commentsPerFollower": 0,
+ "likesToCommentsRatio": 0,
+ "totalViews": 0,
+ "avgViews": 0,
+ "mediaWithViews": 1,
+ "bestByLikes": {
+ "id": "z1",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/z1.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ "bestByComments": {
+ "id": "z1",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/z1.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ "worstByLikes": {
+ "id": "z3",
+ "caption": "",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/z3.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z3/",
+ "timestamp": "2026-08-03T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": 0
+ },
+ "recentMedia": [
+ {
+ "id": "z1",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/z1.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "z2",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/z2.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z2/",
+ "timestamp": "2026-08-02T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "z3",
+ "caption": "",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/z3.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z3/",
+ "timestamp": "2026-08-03T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": 0
+ }
+ ],
+ "contentTypeStats": {
+ "reel": {
+ "count": 1,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 1,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "post": {
+ "count": 2,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ },
+ "video": {
+ "count": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "totalViews": 0,
+ "viewsReported": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0,
+ "avgViews": 0
+ }
+ },
+ "postFrequency": {
+ "perWeek": 10.5,
+ "perMonth": 45
+ },
+ "topPosts": [
+ {
+ "id": "z1",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/z1.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null,
+ "engagement": 0
+ },
+ {
+ "id": "z2",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn.example/z2.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z2/",
+ "timestamp": "2026-08-02T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null,
+ "engagement": 0
+ },
+ {
+ "id": "z3",
+ "caption": "",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn.example/z3.jpg",
+ "thumbnailUrl": "",
+ "permalink": "https://www.instagram.com/p/z3/",
+ "timestamp": "2026-08-03T10:00:00+0000",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": 0,
+ "engagement": 0
+ }
+ ],
+ "postsByDayOfWeek": [
+ {
+ "day": "Sunday",
+ "shortDay": "Sun",
+ "posts": 1,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Monday",
+ "shortDay": "Mon",
+ "posts": 1,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Tuesday",
+ "shortDay": "Tue",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Wednesday",
+ "shortDay": "Wed",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Thursday",
+ "shortDay": "Thu",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Friday",
+ "shortDay": "Fri",
+ "posts": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ },
+ {
+ "day": "Saturday",
+ "shortDay": "Sat",
+ "posts": 1,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingDay": "Sunday",
+ "postsByHour": [
+ {
+ "hour": 0,
+ "label": "0:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 1,
+ "label": "1:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 2,
+ "label": "2:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 3,
+ "label": "3:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 4,
+ "label": "4:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 5,
+ "label": "5:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 6,
+ "label": "6:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 7,
+ "label": "7:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 8,
+ "label": "8:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 9,
+ "label": "9:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 10,
+ "label": "10:00",
+ "posts": 3,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 11,
+ "label": "11:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 12,
+ "label": "12:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 13,
+ "label": "13:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 14,
+ "label": "14:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 15,
+ "label": "15:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 16,
+ "label": "16:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 17,
+ "label": "17:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 18,
+ "label": "18:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 19,
+ "label": "19:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 20,
+ "label": "20:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 21,
+ "label": "21:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 22,
+ "label": "22:00",
+ "posts": 0,
+ "avgEngagement": 0
+ },
+ {
+ "hour": 23,
+ "label": "23:00",
+ "posts": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "bestPostingHour": "",
+ "engagementTimeline": [
+ {
+ "month": "2026-08",
+ "posts": 3,
+ "likes": 0,
+ "comments": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "engagement": 0
+ }
+ ],
+ "monthlyBreakdown": [
+ {
+ "month": "2026-08",
+ "posts": 3,
+ "likes": 0,
+ "comments": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "engagement": 0
+ }
+ ],
+ "postsLast7Days": 0,
+ "postsLast30Days": 1,
+ "postsLast90Days": 3,
+ "hashtagAnalysis": [],
+ "captionLengthCorrelation": [
+ {
+ "label": "No caption",
+ "count": 3,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "avgEngagement": 0
+ }
+ ],
+ "viralityScore": 0,
+ "consistencyScore": 100
+}
diff --git a/backend/services/fixtures/instagramApi.errors.golden.json b/backend/services/fixtures/instagramApi.errors.golden.json
new file mode 100644
index 0000000..327ec6e
--- /dev/null
+++ b/backend/services/fixtures/instagramApi.errors.golden.json
@@ -0,0 +1,14 @@
+[
+ {
+ "error": "Invalid OAuth access token"
+ },
+ {
+ "error": "Legacy message"
+ },
+ {
+ "error": "{\"code\":190}"
+ },
+ {
+ "error": "Top-level message"
+ }
+]
diff --git a/backend/services/fixtures/instagramApi.network.golden.json b/backend/services/fixtures/instagramApi.network.golden.json
new file mode 100644
index 0000000..e498f9a
--- /dev/null
+++ b/backend/services/fixtures/instagramApi.network.golden.json
@@ -0,0 +1,27 @@
+{
+ "outcomes": [
+ {
+ "value": {
+ "igUserId": "7",
+ "name": "",
+ "username": "retried",
+ "profilePictureUrl": "",
+ "followersCount": 0,
+ "followsCount": 0,
+ "mediaCount": 0,
+ "biography": "",
+ "website": ""
+ }
+ },
+ {
+ "error": "Instagram API request timed out"
+ },
+ {
+ "error": "Instagram API unreachable (read ECONNRESET)"
+ },
+ {
+ "error": "Instagram API unreachable (certificate expired)"
+ }
+ ],
+ "requestCount": 7
+}
diff --git a/backend/services/fixtures/instagramApi.profile.golden.json b/backend/services/fixtures/instagramApi.profile.golden.json
new file mode 100644
index 0000000..ebda616
--- /dev/null
+++ b/backend/services/fixtures/instagramApi.profile.golden.json
@@ -0,0 +1,51 @@
+{
+ "results": [
+ {
+ "igUserId": "1789",
+ "name": "Ribbon",
+ "username": "ribbon",
+ "profilePictureUrl": "https://cdn/p.jpg",
+ "followersCount": 2500,
+ "followsCount": 12,
+ "mediaCount": 140,
+ "biography": "Bio",
+ "website": "https://ribbon.example"
+ },
+ {
+ "igUserId": "42",
+ "name": "",
+ "username": "",
+ "profilePictureUrl": "",
+ "followersCount": 0,
+ "followsCount": 0,
+ "mediaCount": 0,
+ "biography": "",
+ "website": ""
+ },
+ {
+ "igUserId": "555",
+ "name": "",
+ "username": "",
+ "profilePictureUrl": "",
+ "followersCount": 0,
+ "followsCount": 0,
+ "mediaCount": 0,
+ "biography": "",
+ "website": ""
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://graph.instagram.com/v25.0/1789?access_token=TOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/me?access_token=TOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/555?access_token=TOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/instagramContentTypes.summary.golden.json b/backend/services/fixtures/instagramContentTypes.summary.golden.json
new file mode 100644
index 0000000..5e84f41
--- /dev/null
+++ b/backend/services/fixtures/instagramContentTypes.summary.golden.json
@@ -0,0 +1,99 @@
+{
+ "types": [
+ "reel",
+ "post",
+ "video"
+ ],
+ "rich": {
+ "reel": {
+ "count": 4,
+ "likes": 1008,
+ "comments": 141,
+ "views": 47400,
+ "viewsReported": 4
+ },
+ "post": {
+ "count": 7,
+ "likes": 142,
+ "comments": 16,
+ "views": 100,
+ "viewsReported": 1
+ },
+ "video": {
+ "count": 2,
+ "likes": 105,
+ "comments": 14,
+ "views": 3300,
+ "viewsReported": 2
+ }
+ },
+ "generated": {
+ "reel": {
+ "count": 8,
+ "likes": 708,
+ "comments": 84,
+ "views": 7200,
+ "viewsReported": 6
+ },
+ "post": {
+ "count": 8,
+ "likes": 804,
+ "comments": 142,
+ "views": 7200,
+ "viewsReported": 6
+ },
+ "video": {
+ "count": 8,
+ "likes": 700,
+ "comments": 110,
+ "views": 7200,
+ "viewsReported": 6
+ }
+ },
+ "odd": {
+ "reel": {
+ "count": 1,
+ "likes": 0,
+ "comments": 0,
+ "views": 0,
+ "viewsReported": 0
+ },
+ "post": {
+ "count": 1,
+ "likes": 3,
+ "comments": 0,
+ "views": 0,
+ "viewsReported": 1
+ },
+ "video": {
+ "count": 1,
+ "likes": 1,
+ "comments": 1,
+ "views": "[NaN]",
+ "viewsReported": 1
+ }
+ },
+ "missing": {
+ "reel": {
+ "count": 0,
+ "likes": 0,
+ "comments": 0,
+ "views": 0,
+ "viewsReported": 0
+ },
+ "post": {
+ "count": 0,
+ "likes": 0,
+ "comments": 0,
+ "views": 0,
+ "viewsReported": 0
+ },
+ "video": {
+ "count": 0,
+ "likes": 0,
+ "comments": 0,
+ "views": 0,
+ "viewsReported": 0
+ }
+ }
+}
diff --git a/backend/services/fixtures/instagramFixtures.js b/backend/services/fixtures/instagramFixtures.js
new file mode 100644
index 0000000..1145e58
--- /dev/null
+++ b/backend/services/fixtures/instagramFixtures.js
@@ -0,0 +1,58 @@
+export const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
+
+function mediaItem(id, contentType, timestamp, counts, caption = '') {
+ const [likeCount, commentsCount, viewCount] = counts;
+ return {
+ id,
+ caption,
+ contentType,
+ mediaType: contentType === 'post' ? 'IMAGE' : 'VIDEO',
+ mediaUrl: `https://cdn.example/${id}.jpg`,
+ thumbnailUrl: '',
+ permalink: `https://www.instagram.com/p/${id}/`,
+ timestamp,
+ likeCount,
+ commentsCount,
+ viewCount,
+ };
+}
+
+const longCaption = `${'Behind the scenes of the shoot. '.repeat(6)}#Café #travel #reels`;
+
+export const richMedia = [
+ mediaItem('m01', 'reel', '2026-08-31T09:15:00+0000', [120, 14, 5400], '#Travel #sunset golden hour over the bay'),
+ mediaItem('m02', 'post', '2026-08-29T18:40:00+0000', [45, 3, null]),
+ mediaItem('m03', 'video', '2026-08-25T09:05:00+0000', [45, 9, 800], 'Short clip #travel'),
+ mediaItem('m04', 'reel', '2026-08-10T21:00:00+0000', [300, 40, 12000], longCaption),
+ mediaItem('m05', 'post', 'not-a-date', [10, 1, null], `${'x'.repeat(320)} #longform`),
+ mediaItem('m06', 'post', '2026-07-14T06:30:00+0000', [0, 0, null], '#quiet'),
+ mediaItem('m07', 'reel', '2026-07-02T12:00:00+0000', [88, 12, 0], `${'m'.repeat(70)} #reels #Àpropos`),
+ mediaItem('m08', 'story', '2026-06-20T23:59:00+0000', [15, 2, 100], 'Unknown type'),
+ mediaItem('m09', 'post', '2026-06-03T00:00:00+0000', [45, 9, null], 'a'.repeat(50)),
+ mediaItem('m10', 'video', '2026-05-01T15:45:00+0000', [60, 5, 2500], 'b'.repeat(151)),
+ mediaItem('m11', 'post', '2026-03-15T08:00:00+0000', [22, 0, null], 'c'.repeat(300)),
+ mediaItem('m12', 'reel', '2025-12-31T23:30:00+0000', [500, 75, 30000], '#Travel #TRAVEL #newyear'),
+ mediaItem('m13', 'post', '', [5, 1, null], '#travel'),
+];
+
+export const zeroEngagementMedia = [
+ mediaItem('z1', 'post', '2026-08-01T10:00:00+0000', [0, 0, null]),
+ mediaItem('z2', 'post', '2026-08-02T10:00:00+0000', [0, 0, null]),
+ mediaItem('z3', 'reel', '2026-08-03T10:00:00+0000', [0, 0, 0]),
+];
+
+function generatedCaption(index) {
+ const tags = [];
+ for (let tag = 0; tag < 25; tag++) {
+ if ((tag + index) % 3 === 0) tags.push(`#tag${tag}`);
+ }
+ return `Post number ${index} ${tags.join(' ')}`;
+}
+
+export const generatedMedia = Array.from({ length: 24 }, (_, index) => mediaItem(
+ `g${String(index).padStart(2, '0')}`,
+ ['reel', 'post', 'video'][index % 3],
+ new Date(Date.UTC(2026, 7, 30, 20) - index * 3.5 * 86400000).toISOString().replace('.000Z', '+0000'),
+ [(index * 37) % 200, (index * 11) % 30, index % 4 === 0 ? null : index * 100],
+ generatedCaption(index),
+));
diff --git a/backend/services/fixtures/instagramMedia.normalize.golden.json b/backend/services/fixtures/instagramMedia.normalize.golden.json
new file mode 100644
index 0000000..d621952
--- /dev/null
+++ b/backend/services/fixtures/instagramMedia.normalize.golden.json
@@ -0,0 +1,121 @@
+[
+ {
+ "type": "reel",
+ "views": 300,
+ "normalized": {
+ "id": "1",
+ "caption": "Reel",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn/v.mp4",
+ "thumbnailUrl": "https://cdn/c.jpg",
+ "permalink": "https://www.instagram.com/reel/1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 9,
+ "commentsCount": 2,
+ "viewCount": 300
+ }
+ },
+ {
+ "type": "post",
+ "views": null,
+ "normalized": {
+ "id": "2",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/i.jpg",
+ "thumbnailUrl": "https://cdn/i.jpg",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ },
+ {
+ "type": "video",
+ "views": 41,
+ "normalized": {
+ "id": "3",
+ "caption": "",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "",
+ "thumbnailUrl": "https://cdn/t3.jpg",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": 41
+ }
+ },
+ {
+ "type": "post",
+ "views": null,
+ "normalized": {
+ "id": "4",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "CAROUSEL_ALBUM",
+ "mediaUrl": "",
+ "thumbnailUrl": "",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ },
+ {
+ "type": "reel",
+ "views": null,
+ "normalized": {
+ "id": "5",
+ "caption": "",
+ "contentType": "reel",
+ "mediaType": "IMAGE",
+ "mediaUrl": "",
+ "thumbnailUrl": "",
+ "permalink": "https://instagram.com/reels/5/",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ },
+ {
+ "type": "reel",
+ "views": null,
+ "normalized": {
+ "id": "6",
+ "caption": "",
+ "contentType": "reel",
+ "mediaType": "REEL",
+ "mediaUrl": "",
+ "thumbnailUrl": "",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ },
+ {
+ "type": "post",
+ "views": null,
+ "normalized": {
+ "id": "7",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "",
+ "thumbnailUrl": "",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ }
+]
diff --git a/backend/services/fixtures/instagramMedia.pageCap.golden.json b/backend/services/fixtures/instagramMedia.pageCap.golden.json
new file mode 100644
index 0000000..0529219
--- /dev/null
+++ b/backend/services/fixtures/instagramMedia.pageCap.golden.json
@@ -0,0 +1,15 @@
+{
+ "ids": [
+ "p1",
+ "p2",
+ "p3",
+ "p4",
+ "p5",
+ "p6",
+ "p7",
+ "p8",
+ "p9",
+ "p10"
+ ],
+ "requestCount": 10
+}
diff --git a/backend/services/fixtures/instagramMedia.paging.golden.json b/backend/services/fixtures/instagramMedia.paging.golden.json
new file mode 100644
index 0000000..0aec3ff
--- /dev/null
+++ b/backend/services/fixtures/instagramMedia.paging.golden.json
@@ -0,0 +1,106 @@
+{
+ "media": [
+ {
+ "id": "1",
+ "caption": "Reel",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn/v.mp4",
+ "thumbnailUrl": "https://cdn/c.jpg",
+ "permalink": "https://www.instagram.com/reel/1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 9,
+ "commentsCount": 2,
+ "viewCount": 300
+ },
+ {
+ "id": "2",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/i.jpg",
+ "thumbnailUrl": "https://cdn/i.jpg",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ },
+ {
+ "id": "3",
+ "caption": "",
+ "contentType": "video",
+ "mediaType": "VIDEO",
+ "mediaUrl": "",
+ "thumbnailUrl": "https://cdn/t3.jpg",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": 41
+ },
+ {
+ "id": "4",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "CAROUSEL_ALBUM",
+ "mediaUrl": "",
+ "thumbnailUrl": "",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ ],
+ "limited": [
+ {
+ "id": "1",
+ "caption": "Reel",
+ "contentType": "reel",
+ "mediaType": "VIDEO",
+ "mediaUrl": "https://cdn/v.mp4",
+ "thumbnailUrl": "https://cdn/c.jpg",
+ "permalink": "https://www.instagram.com/reel/1/",
+ "timestamp": "2026-08-01T10:00:00+0000",
+ "likeCount": 9,
+ "commentsCount": 2,
+ "viewCount": 300
+ },
+ {
+ "id": "2",
+ "caption": "",
+ "contentType": "post",
+ "mediaType": "IMAGE",
+ "mediaUrl": "https://cdn/i.jpg",
+ "thumbnailUrl": "https://cdn/i.jpg",
+ "permalink": "",
+ "timestamp": "",
+ "likeCount": 0,
+ "commentsCount": 0,
+ "viewCount": null
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://graph.instagram.com/v25.0/17841/media?access_token=TOKEN&limit=50&fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Ccover_url%2Cpermalink%2Ctimestamp%2Clike_count%2Ccomments_count%2Cinsights.metric%28views%29",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/17841/media?access_token=TOKEN&limit=50&after=p2&fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Ccover_url%2Cpermalink%2Ctimestamp%2Clike_count%2Ccomments_count%2Cinsights.metric%28views%29",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/17841/media?access_token=TOKEN&limit=50&after=p2&fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Ccover_url%2Cpermalink%2Ctimestamp%2Clike_count%2Ccomments_count",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/17841/media?access_token=TOKEN&limit=50&after=p3&fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Ccover_url%2Cpermalink%2Ctimestamp%2Clike_count%2Ccomments_count%2Cinsights.metric%28views%29",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/v25.0/17841/media?access_token=TOKEN&limit=50&fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Ccover_url%2Cpermalink%2Ctimestamp%2Clike_count%2Ccomments_count%2Cinsights.metric%28views%29",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/instagramPublishing.params.golden.json b/backend/services/fixtures/instagramPublishing.params.golden.json
new file mode 100644
index 0000000..0cdae21
--- /dev/null
+++ b/backend/services/fixtures/instagramPublishing.params.golden.json
@@ -0,0 +1,164 @@
+{
+ "results": [
+ {
+ "mediaType": "CAROUSEL",
+ "full": {
+ "access_token": "TOKEN",
+ "media_type": "CAROUSEL",
+ "caption": "Caption #tag",
+ "children": "c1,c2,c3",
+ "collaborators": "[\"partner_one\",\"partner_two\"]",
+ "location_id": "110"
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "media_type": "CAROUSEL"
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "media_type": "CAROUSEL"
+ }
+ },
+ {
+ "mediaType": "CAROUSEL_ITEM_IMAGE",
+ "full": {
+ "access_token": "TOKEN",
+ "image_url": "https://cdn.example/file.jpg",
+ "is_carousel_item": true
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "image_url": "https://cdn.example/file.mov",
+ "is_carousel_item": true
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "image_url": "[undefined]",
+ "is_carousel_item": true
+ }
+ },
+ {
+ "mediaType": "CAROUSEL_ITEM_VIDEO",
+ "full": {
+ "access_token": "TOKEN",
+ "media_type": "VIDEO",
+ "video_url": "https://cdn.example/file.jpg",
+ "is_carousel_item": true
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "media_type": "VIDEO",
+ "video_url": "https://cdn.example/file.mov",
+ "is_carousel_item": true
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "media_type": "VIDEO",
+ "video_url": "[undefined]",
+ "is_carousel_item": true
+ }
+ },
+ {
+ "mediaType": "REELS",
+ "full": {
+ "access_token": "TOKEN",
+ "media_type": "REELS",
+ "video_url": "https://cdn.example/file.jpg",
+ "caption": "Caption #tag",
+ "share_to_feed": true,
+ "cover_url": "https://cdn.example/cover.jpg",
+ "collaborators": "[\"partner_one\",\"partner_two\"]",
+ "audio_name": "Original audio",
+ "thumb_offset": 1500,
+ "location_id": "110",
+ "user_tags": "[{\"username\":\"friend\",\"x\":0.5,\"y\":0.5}]"
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "media_type": "REELS",
+ "video_url": "https://cdn.example/file.mov"
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "media_type": "REELS",
+ "video_url": "[undefined]"
+ }
+ },
+ {
+ "mediaType": "STORIES",
+ "full": {
+ "access_token": "TOKEN",
+ "media_type": "STORIES",
+ "image_url": "https://cdn.example/file.jpg",
+ "user_tags": "[{\"username\":\"friend\",\"x\":0.5,\"y\":0.5}]"
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "media_type": "STORIES",
+ "video_url": "https://cdn.example/file.mov"
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "media_type": "STORIES",
+ "image_url": "[undefined]"
+ }
+ },
+ {
+ "mediaType": "IMAGE",
+ "full": {
+ "access_token": "TOKEN",
+ "image_url": "https://cdn.example/file.jpg",
+ "caption": "Caption #tag",
+ "location_id": "110",
+ "user_tags": "[{\"username\":\"friend\",\"x\":0.5,\"y\":0.5}]",
+ "alt_text": "A ribbon on a table"
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "image_url": "https://cdn.example/file.mov"
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "image_url": "[undefined]"
+ }
+ },
+ {
+ "mediaType": "none",
+ "full": {
+ "access_token": "TOKEN",
+ "image_url": "https://cdn.example/file.jpg",
+ "caption": "Caption #tag",
+ "location_id": "110",
+ "user_tags": "[{\"username\":\"friend\",\"x\":0.5,\"y\":0.5}]",
+ "alt_text": "A ribbon on a table"
+ },
+ "empty": {
+ "access_token": "TOKEN",
+ "image_url": "https://cdn.example/file.mov"
+ },
+ "bare": {
+ "access_token": "TOKEN",
+ "image_url": "[undefined]"
+ }
+ }
+ ],
+ "variants": [
+ {
+ "access_token": "T",
+ "media_type": "REELS",
+ "video_url": "https://cdn/v.mp4",
+ "share_to_feed": false,
+ "thumb_offset": 0
+ },
+ {
+ "access_token": "T",
+ "media_type": "STORIES",
+ "video_url": "https://cdn/story.WEBM?x=1"
+ },
+ {
+ "access_token": "T",
+ "media_type": "STORIES",
+ "video_url": "https://cdn/story.avi.jpg"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/instagramTokens.autoRefresh.golden.json b/backend/services/fixtures/instagramTokens.autoRefresh.golden.json
new file mode 100644
index 0000000..b00152a
--- /dev/null
+++ b/backend/services/fixtures/instagramTokens.autoRefresh.golden.json
@@ -0,0 +1,166 @@
+{
+ "lines": [
+ [
+ "log",
+ "Token refreshed for @soon - expires 2026-10-31T12:00:00.000Z"
+ ],
+ [
+ "error",
+ "Failed to refresh token for @failing: Session has expired"
+ ],
+ [
+ "log",
+ "Token refreshed for @expired - expires 2026-10-31T12:00:00.000Z"
+ ]
+ ],
+ "requests": [
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=T1",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=T6",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=T7",
+ "method": "GET"
+ }
+ ],
+ "calls": [
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": []
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "a1"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "accounts",
+ "values": {
+ "platform": "instagram",
+ "data": {
+ "username": "soon",
+ "accessToken": "N1",
+ "tokenExpiresAt": "2026-10-31T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "a1"
+ ]
+ ]
+ },
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": [
+ [
+ "id",
+ "a7"
+ ]
+ ]
+ },
+ {
+ "type": "update",
+ "table": "accounts",
+ "values": {
+ "platform": "instagram",
+ "data": {
+ "username": "expired",
+ "accessToken": "N7",
+ "tokenExpiresAt": "2026-10-31T12:00:00.000Z"
+ }
+ },
+ "filters": [
+ [
+ "id",
+ "a7"
+ ]
+ ]
+ }
+ ],
+ "table": [
+ {
+ "id": "a1",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "username": "soon",
+ "accessToken": "N1",
+ "tokenExpiresAt": "2026-10-31T12:00:00.000Z"
+ }
+ },
+ {
+ "id": "a2",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "username": "later",
+ "accessToken": "T2",
+ "tokenExpiresAt": "2026-10-11T12:00:00.000Z"
+ }
+ },
+ {
+ "id": "a3",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "username": "notoken",
+ "tokenExpiresAt": "2026-09-02T12:00:00.000Z"
+ }
+ },
+ {
+ "id": "a4",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "username": "noexpiry",
+ "accessToken": "T4"
+ }
+ },
+ {
+ "id": "a5",
+ "platform": "youtube",
+ "user_id": "user-1",
+ "data": {
+ "channelId": "UC1",
+ "accessToken": "T5",
+ "tokenExpiresAt": "2026-09-02T12:00:00.000Z"
+ }
+ },
+ {
+ "id": "a6",
+ "platform": "instagram",
+ "user_id": "user-1",
+ "data": {
+ "username": "failing",
+ "accessToken": "T6",
+ "tokenExpiresAt": "2026-09-16T12:00:00.000Z"
+ }
+ },
+ {
+ "id": "a7",
+ "platform": "instagram",
+ "user_id": "user-2",
+ "data": {
+ "username": "expired",
+ "accessToken": "N7",
+ "tokenExpiresAt": "2026-10-31T12:00:00.000Z"
+ }
+ }
+ ]
+}
diff --git a/backend/services/fixtures/instagramTokens.exchange.golden.json b/backend/services/fixtures/instagramTokens.exchange.golden.json
new file mode 100644
index 0000000..4b32c5a
--- /dev/null
+++ b/backend/services/fixtures/instagramTokens.exchange.golden.json
@@ -0,0 +1,64 @@
+{
+ "outcomes": [
+ {
+ "value": {
+ "accessToken": "LONG",
+ "tokenType": "Bearer",
+ "expiresIn": 3600
+ }
+ },
+ {
+ "value": {
+ "accessToken": "LONG2",
+ "tokenType": "bearer",
+ "expiresIn": 5184000
+ }
+ },
+ {
+ "error": "Failed to exchange token - check Instagram App Secret"
+ },
+ {
+ "value": {
+ "accessToken": "REFRESHED",
+ "tokenType": "bearer",
+ "expiresIn": 7200
+ }
+ },
+ {
+ "value": {
+ "accessToken": "REFRESHED2",
+ "tokenType": "bearer",
+ "expiresIn": 5184000
+ }
+ },
+ {
+ "error": "Failed to refresh token"
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=SECRET&access_token=SHORT",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=SECRET&access_token=SHORT",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=SECRET&access_token=SHORT",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
+ "method": "GET"
+ },
+ {
+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=LONG",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/instagramTokens.idle.golden.json b/backend/services/fixtures/instagramTokens.idle.golden.json
new file mode 100644
index 0000000..5e60d59
--- /dev/null
+++ b/backend/services/fixtures/instagramTokens.idle.golden.json
@@ -0,0 +1,18 @@
+{
+ "lines": [
+ [
+ "error",
+ "autoRefreshInstagramTokens error:",
+ "database unavailable"
+ ]
+ ],
+ "requests": [],
+ "calls": [
+ {
+ "type": "select",
+ "table": "accounts",
+ "columns": "id, platform, data",
+ "filters": []
+ }
+ ]
+}
diff --git a/backend/services/instagram.js b/backend/services/instagram.js
index 52b4bc4..2d5cfc4 100644
--- a/backend/services/instagram.js
+++ b/backend/services/instagram.js
@@ -1,469 +1,8 @@
-// fetch is a global in Cloudflare Workers - no import needed.
-import { getAccounts, updateAccount } from '../lib/db.js';
-
-const IG_GRAPH_URL = 'https://graph.instagram.com';
-const IG_API_VERSION = 'v25.0';
-
-async function igFetch(endpoint, params = {}, retries = 1) {
- const needsVersion = !endpoint.startsWith('/oauth') &&
- !endpoint.startsWith('/access_token') &&
- !endpoint.startsWith('/refresh_access_token');
- const base = needsVersion ? `${IG_GRAPH_URL}/${IG_API_VERSION}` : IG_GRAPH_URL;
- const url = new URL(`${base}${endpoint}`);
- Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
-
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), 15000);
-
- let res;
- try {
- res = await fetch(url.toString(), { signal: controller.signal });
- } catch (err) {
- clearTimeout(timer);
- const isTransient = err.name === 'AbortError' ||
- err.message?.includes('EAI_AGAIN') ||
- err.message?.includes('ECONNRESET');
- if (isTransient && retries > 0) {
- await new Promise(r => setTimeout(r, 1000));
- return igFetch(endpoint, params, retries - 1);
- }
- if (err.name === 'AbortError') throw new Error('Instagram API request timed out');
- throw new Error(`Instagram API unreachable (${err.message})`);
- }
- clearTimeout(timer);
-
- const data = await res.json();
- if (data.error) throw new Error(data.error.message || data.error.error_message || JSON.stringify(data.error));
- if (data.error_message) throw new Error(data.error_message);
- return data;
-}
-
-export async function exchangeForLongLivedToken(shortToken, appSecret) {
- const data = await igFetch('/access_token', {
- grant_type: 'ig_exchange_token',
- client_secret: appSecret,
- access_token: shortToken,
- });
- if (!data.access_token) throw new Error('Failed to exchange token - check Instagram App Secret');
- return {
- accessToken: data.access_token,
- tokenType: data.token_type || 'bearer',
- expiresIn: data.expires_in || 5184000,
- };
-}
-
-export async function refreshLongLivedToken(longToken) {
- const data = await igFetch('/refresh_access_token', {
- grant_type: 'ig_refresh_token',
- access_token: longToken,
- });
- if (!data.access_token) throw new Error('Failed to refresh token');
- return {
- accessToken: data.access_token,
- tokenType: data.token_type || 'bearer',
- expiresIn: data.expires_in || 5184000,
- };
-}
-
-// Called by the daily cron trigger. Receives supabase so it works outside of
-// a request context (no Hono context available in cron handlers).
-export async function autoRefreshInstagramTokens(supabase) {
- try {
- const accounts = await getAccounts(supabase);
- const igAccounts = accounts.filter(a => a.platform === 'instagram' && a.accessToken && a.tokenExpiresAt);
- if (igAccounts.length === 0) return;
-
- const fifteenDaysMs = 15 * 24 * 60 * 60 * 1000;
- const soon = new Date(Date.now() + fifteenDaysMs);
- const toRefresh = igAccounts.filter(a => new Date(a.tokenExpiresAt) <= soon);
- if (toRefresh.length === 0) return;
-
- for (const account of toRefresh) {
- try {
- const refreshed = await refreshLongLivedToken(account.accessToken);
- const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || 5184000) * 1000).toISOString();
- await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt });
- console.log(`Token refreshed for @${account.username} - expires ${tokenExpiresAt}`);
- } catch (err) {
- console.error(`Failed to refresh token for @${account.username}: ${err.message}`);
- }
- }
- } catch (err) {
- console.error('autoRefreshInstagramTokens error:', err.message);
- }
-}
-
-export async function fetchInstagramProfile(igUserId, accessToken) {
- const endpoint = igUserId ? `/${igUserId}` : '/me';
- const data = await igFetch(endpoint, {
- access_token: accessToken,
- fields: 'user_id,username,name,profile_picture_url,followers_count,follows_count,media_count,biography,website',
- });
- return {
- igUserId: data.user_id || data.id || igUserId,
- name: data.name || '',
- username: data.username || '',
- profilePictureUrl: data.profile_picture_url || '',
- followersCount: data.followers_count || 0,
- followsCount: data.follows_count || 0,
- mediaCount: data.media_count || 0,
- biography: data.biography || '',
- website: data.website || '',
- };
-}
-
-export const CONTENT_TYPES = ['reel', 'post', 'video'];
-
-const MEDIA_FIELDS = 'id,caption,media_type,media_product_type,media_url,thumbnail_url,cover_url,permalink,timestamp,like_count,comments_count';
-const VIEWS_FIELD = 'insights.metric(views)';
-const MEDIA_PAGE_SIZE = 50;
-const MAX_MEDIA_PAGES = 10;
-const REEL_PERMALINK = /instagram\.com\/reels?\//i;
-
-// media_type never says REELS - Instagram reports reels as VIDEO and only media_product_type tells them apart.
-export function classifyInstagramMedia(raw) {
- const productType = String(raw?.media_product_type || '').toUpperCase();
- const mediaType = String(raw?.media_type || '').toUpperCase();
-
- if (productType === 'REELS') return 'reel';
- if (!productType && REEL_PERMALINK.test(raw?.permalink || '')) return 'reel';
- if (mediaType === 'REELS' || mediaType === 'REEL') return 'reel';
- if (mediaType === 'VIDEO') return 'video';
- return 'post';
-}
-
-export function extractInstagramViews(raw) {
- const metric = raw?.insights?.data?.find(d => d.name === 'views');
- const value = metric?.values?.[0]?.value ?? metric?.total_value?.value;
- const views = Number(value);
- return value !== undefined && value !== null && Number.isFinite(views) ? views : null;
-}
-
-export function normalizeInstagramMedia(raw) {
- const contentType = classifyInstagramMedia(raw);
- const mediaType = String(raw.media_type || 'IMAGE').toUpperCase();
- return {
- id: raw.id,
- caption: raw.caption || '',
- contentType,
- mediaType,
- mediaUrl: raw.media_url || '',
- thumbnailUrl: raw.cover_url || raw.thumbnail_url || (contentType === 'post' ? raw.media_url || '' : ''),
- permalink: raw.permalink || '',
- timestamp: raw.timestamp || '',
- likeCount: raw.like_count || 0,
- commentsCount: raw.comments_count || 0,
- viewCount: extractInstagramViews(raw),
- };
-}
-
-async function fetchMediaPage(igUserId, accessToken, after) {
- const params = { access_token: accessToken, limit: String(MEDIA_PAGE_SIZE) };
- if (after) params.after = after;
- try {
- return await igFetch(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` });
- } catch {
- // One item without insights (e.g. posted before the account went professional) fails the whole page.
- return igFetch(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS });
- }
-}
-
-export async function fetchInstagramMedia(igUserId, accessToken, limit = 500) {
- const allMedia = [];
- let after = null;
-
- for (let page = 0; page < MAX_MEDIA_PAGES && allMedia.length < limit; page++) {
- const data = await fetchMediaPage(igUserId, accessToken, after);
- if (Array.isArray(data.data)) allMedia.push(...data.data);
- after = data.paging?.next ? data.paging?.cursors?.after : null;
- if (!after) break;
- }
-
- const unique = new Map();
- allMedia.forEach(m => { if (m?.id && !unique.has(m.id)) unique.set(m.id, m); });
- return [...unique.values()].slice(0, limit).map(normalizeInstagramMedia);
-}
-
-export function summarizeContentTypes(media) {
- const summary = {};
- CONTENT_TYPES.forEach(type => {
- summary[type] = { count: 0, likes: 0, comments: 0, views: 0, viewsReported: 0 };
- });
- (media || []).forEach(m => {
- const s = summary[CONTENT_TYPES.includes(m.contentType) ? m.contentType : 'post'];
- s.count++;
- s.likes += m.likeCount || 0;
- s.comments += m.commentsCount || 0;
- if (typeof m.viewCount === 'number') {
- s.views += m.viewCount;
- s.viewsReported++;
- }
- });
- return summary;
-}
-
-function buildContentTypeStats(media) {
- const summary = summarizeContentTypes(media);
- const stats = {};
- CONTENT_TYPES.forEach(type => {
- const s = summary[type];
- stats[type] = {
- count: s.count,
- totalLikes: s.likes,
- totalComments: s.comments,
- totalViews: s.views,
- viewsReported: s.viewsReported,
- avgLikes: s.count > 0 ? Math.round(s.likes / s.count) : 0,
- avgComments: s.count > 0 ? Math.round(s.comments / s.count) : 0,
- avgEngagement: s.count > 0 ? Math.round((s.likes + s.comments) / s.count) : 0,
- avgViews: s.viewsReported > 0 ? Math.round(s.views / s.viewsReported) : 0,
- };
- });
- return stats;
-}
-
-export function computeInstagramAnalytics(profile, media) {
- const emptyAnalytics = {
- totalPosts: profile.mediaCount || 0, fetchedPosts: 0,
- totalLikes: 0, totalComments: 0, totalEngagement: 0,
- avgLikes: 0, avgComments: 0, avgEngagement: 0,
- medianLikes: 0, medianComments: 0,
- engagementRate: 0, likesPerFollower: 0, commentsPerFollower: 0,
- totalViews: 0, avgViews: 0, mediaWithViews: 0,
- bestByLikes: null, bestByComments: null, worstByLikes: null,
- recentMedia: [], contentTypeStats: buildContentTypeStats([]),
- postFrequency: { perWeek: 0, perMonth: 0 },
- topPosts: [],
- hashtagAnalysis: [], captionLengthCorrelation: [],
- postsByDayOfWeek: [], postsByHour: [],
- engagementTimeline: [], monthlyBreakdown: [],
- postsLast7Days: 0, postsLast30Days: 0, postsLast90Days: 0,
- viralityScore: 0, consistencyScore: 0,
- bestPostingDay: '', bestPostingHour: '',
- likesToCommentsRatio: 0,
- };
- if (!media || media.length === 0) return emptyAnalytics;
-
- const totalLikes = media.reduce((s, m) => s + m.likeCount, 0);
- const totalComments = media.reduce((s, m) => s + m.commentsCount, 0);
- const totalEngagement = totalLikes + totalComments;
- const avgLikes = Math.round(totalLikes / media.length);
- const avgComments = Math.round(totalComments / media.length);
- const avgEngagement = Math.round(totalEngagement / media.length);
- const engagementRate = profile.followersCount > 0
- ? parseFloat(((totalLikes + totalComments) / media.length / profile.followersCount * 100).toFixed(2)) : 0;
- const likesPerFollower = profile.followersCount > 0
- ? parseFloat((totalLikes / media.length / profile.followersCount * 100).toFixed(2)) : 0;
- const commentsPerFollower = profile.followersCount > 0
- ? parseFloat((totalComments / media.length / profile.followersCount * 100).toFixed(2)) : 0;
-
- const sortedLikes = [...media].map(m => m.likeCount).sort((a, b) => a - b);
- const sortedComments = [...media].map(m => m.commentsCount).sort((a, b) => a - b);
- const mid = Math.floor(sortedLikes.length / 2);
- const medianLikes = sortedLikes.length % 2 ? sortedLikes[mid] : Math.round((sortedLikes[mid - 1] + sortedLikes[mid]) / 2);
- const medianComments = sortedComments.length % 2 ? sortedComments[mid] : Math.round((sortedComments[mid - 1] + sortedComments[mid]) / 2);
-
- const byLikes = [...media].sort((a, b) => b.likeCount - a.likeCount);
- const byComments = [...media].sort((a, b) => b.commentsCount - a.commentsCount);
- const likesToCommentsRatio = totalComments > 0 ? parseFloat((totalLikes / totalComments).toFixed(1)) : 0;
-
- const contentTypeStats = buildContentTypeStats(media);
- const mediaWithViews = CONTENT_TYPES.reduce((s, t) => s + contentTypeStats[t].viewsReported, 0);
- const totalViews = CONTENT_TYPES.reduce((s, t) => s + contentTypeStats[t].totalViews, 0);
- const avgViews = mediaWithViews > 0 ? Math.round(totalViews / mediaWithViews) : 0;
-
- const dates = media.map(m => new Date(m.timestamp)).filter(d => !isNaN(d));
- let perWeek = 0, perMonth = 0;
- if (dates.length >= 2) {
- const newest = Math.max(...dates);
- const oldest = Math.min(...dates);
- const spanDays = Math.max(1, (newest - oldest) / 86400000);
- perWeek = parseFloat((media.length / spanDays * 7).toFixed(1));
- perMonth = parseFloat((media.length / spanDays * 30).toFixed(1));
- }
-
- const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
- const dayBuckets = Array(7).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
- dates.forEach((d, i) => {
- const day = d.getDay();
- dayBuckets[day].count++;
- dayBuckets[day].likes += media[i]?.likeCount || 0;
- dayBuckets[day].comments += media[i]?.commentsCount || 0;
- });
- const postsByDayOfWeek = dayBuckets.map((b, i) => ({
- day: dayNames[i], shortDay: dayNames[i].slice(0, 3),
- posts: b.count,
- avgLikes: b.count > 0 ? Math.round(b.likes / b.count) : 0,
- avgComments: b.count > 0 ? Math.round(b.comments / b.count) : 0,
- avgEngagement: b.count > 0 ? Math.round((b.likes + b.comments) / b.count) : 0,
- }));
- const bestDayObj = postsByDayOfWeek.reduce((best, d) => d.avgEngagement > best.avgEngagement ? d : best, postsByDayOfWeek[0]);
-
- const hourBuckets = Array(24).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
- dates.forEach((d, i) => {
- const h = d.getHours();
- hourBuckets[h].count++;
- hourBuckets[h].likes += media[i]?.likeCount || 0;
- hourBuckets[h].comments += media[i]?.commentsCount || 0;
- });
- const postsByHour = hourBuckets.map((b, i) => ({
- hour: i, label: `${i}:00`,
- posts: b.count,
- avgEngagement: b.count > 0 ? Math.round((b.likes + b.comments) / b.count) : 0,
- }));
- const bestHourObj = postsByHour.reduce((best, h) => h.avgEngagement > best.avgEngagement ? h : best, postsByHour[0]);
-
- const monthMap = {};
- media.forEach(m => {
- const d = new Date(m.timestamp);
- if (isNaN(d)) return;
- const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
- if (!monthMap[key]) monthMap[key] = { posts: 0, likes: 0, comments: 0 };
- monthMap[key].posts++;
- monthMap[key].likes += m.likeCount;
- monthMap[key].comments += m.commentsCount;
- });
- const monthlyBreakdown = Object.entries(monthMap)
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([month, s]) => ({
- month, posts: s.posts,
- likes: s.likes, comments: s.comments,
- avgLikes: Math.round(s.likes / s.posts),
- avgComments: Math.round(s.comments / s.posts),
- engagement: s.likes + s.comments,
- }));
-
- const now = Date.now();
- const postsLast7Days = dates.filter(d => (now - d.getTime()) <= 7 * 86400000).length;
- const postsLast30Days = dates.filter(d => (now - d.getTime()) <= 30 * 86400000).length;
- const postsLast90Days = dates.filter(d => (now - d.getTime()) <= 90 * 86400000).length;
-
- const hashtagMap = {};
- media.forEach(m => {
- const tags = (m.caption || '').match(/#[\wÀ-ɏ]+/g) || [];
- tags.forEach(tag => {
- const t = tag.toLowerCase();
- if (!hashtagMap[t]) hashtagMap[t] = { tag: t, count: 0, likes: 0, comments: 0 };
- hashtagMap[t].count++;
- hashtagMap[t].likes += m.likeCount;
- hashtagMap[t].comments += m.commentsCount;
- });
- });
- const hashtagAnalysis = Object.values(hashtagMap)
- .map(h => ({ ...h, avgEngagement: Math.round((h.likes + h.comments) / h.count) }))
- .sort((a, b) => b.count - a.count)
- .slice(0, 20);
-
- const captionBuckets = [
- { label: 'No caption', min: 0, max: 0 },
- { label: 'Short (1-50)', min: 1, max: 50 },
- { label: 'Medium (51-150)', min: 51, max: 150 },
- { label: 'Long (151-300)', min: 151, max: 300 },
- { label: 'Very Long (300+)', min: 301, max: Infinity },
- ];
- const captionLengthCorrelation = captionBuckets.map(bucket => {
- const posts = media.filter(m => {
- const len = (m.caption || '').length;
- return len >= bucket.min && len <= bucket.max;
- });
- return {
- label: bucket.label, count: posts.length,
- avgLikes: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.likeCount, 0) / posts.length) : 0,
- avgComments: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.commentsCount, 0) / posts.length) : 0,
- avgEngagement: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.likeCount + m.commentsCount, 0) / posts.length) : 0,
- };
- }).filter(b => b.count > 0);
-
- const topPosts = [...media]
- .map(m => ({ ...m, engagement: m.likeCount + m.commentsCount }))
- .sort((a, b) => b.engagement - a.engagement)
- .slice(0, 10);
- const worstByLikes = byLikes.length > 0 ? byLikes[byLikes.length - 1] : null;
-
- const bestEngagement = topPosts[0] ? topPosts[0].engagement : 0;
- const viralityScore = avgEngagement > 0 ? parseFloat((bestEngagement / avgEngagement).toFixed(1)) : 0;
-
- let consistencyScore = 0;
- if (media.length >= 3) {
- const engagements = media.map(m => m.likeCount + m.commentsCount);
- const mean = engagements.reduce((s, v) => s + v, 0) / engagements.length;
- const variance = engagements.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / engagements.length;
- const stdDev = Math.sqrt(variance);
- const cv = mean > 0 ? stdDev / mean : (stdDev > 0 ? 10 : 0);
- consistencyScore = Math.max(0, Math.min(100, Math.round(100 / (1 + cv))));
- }
-
- return {
- totalPosts: profile.mediaCount || media.length,
- fetchedPosts: media.length,
- totalLikes, totalComments, totalEngagement,
- avgLikes, avgComments, avgEngagement,
- medianLikes, medianComments,
- engagementRate, likesPerFollower, commentsPerFollower,
- likesToCommentsRatio,
- totalViews, avgViews, mediaWithViews,
- bestByLikes: byLikes[0] || null,
- bestByComments: byComments[0] || null,
- worstByLikes,
- recentMedia: media.slice(0, 20),
- contentTypeStats,
- postFrequency: { perWeek, perMonth },
- topPosts,
- postsByDayOfWeek, bestPostingDay: bestDayObj?.day || '',
- postsByHour, bestPostingHour: bestHourObj?.posts > 0 ? bestHourObj.label : '',
- engagementTimeline: monthlyBreakdown, monthlyBreakdown,
- postsLast7Days, postsLast30Days, postsLast90Days,
- hashtagAnalysis,
- captionLengthCorrelation,
- viralityScore, consistencyScore,
- };
-}
-
-// Graph API container parameters for one media item. Shared by the publish route and the cron
-// scheduler; scripts/publish-scheduled.js keeps its own copy because it must stay dependency-free.
-export function buildMediaParams(post, accessToken) {
- const { mediaType, mediaUrl, caption, coverUrl, shareToFeed, collaborators, audioName,
- thumbOffset, locationId, userTags, altText, children } = post;
- const params = { access_token: accessToken };
-
- if (mediaType === 'CAROUSEL') {
- params.media_type = 'CAROUSEL';
- if (caption) params.caption = caption;
- if (children?.length) params.children = children.join(',');
- if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);
- if (locationId) params.location_id = locationId;
- } else if (mediaType === 'CAROUSEL_ITEM_IMAGE') {
- params.image_url = mediaUrl;
- params.is_carousel_item = true;
- } else if (mediaType === 'CAROUSEL_ITEM_VIDEO') {
- params.media_type = 'VIDEO';
- params.video_url = mediaUrl;
- params.is_carousel_item = true;
- } else if (mediaType === 'REELS') {
- params.media_type = 'REELS';
- params.video_url = mediaUrl;
- if (caption) params.caption = caption;
- if (shareToFeed !== undefined) params.share_to_feed = shareToFeed;
- if (coverUrl) params.cover_url = coverUrl;
- if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);
- if (audioName) params.audio_name = audioName;
- if (thumbOffset != null) params.thumb_offset = thumbOffset;
- if (locationId) params.location_id = locationId;
- if (userTags?.length) params.user_tags = JSON.stringify(userTags);
- } else if (mediaType === 'STORIES') {
- params.media_type = 'STORIES';
- if (mediaUrl?.match(/\.(mp4|mov|avi|webm)/i)) {
- params.video_url = mediaUrl;
- } else {
- params.image_url = mediaUrl;
- }
- if (userTags?.length) params.user_tags = JSON.stringify(userTags);
- } else {
- params.image_url = mediaUrl;
- if (caption) params.caption = caption;
- if (locationId) params.location_id = locationId;
- if (userTags?.length) params.user_tags = JSON.stringify(userTags);
- if (altText) params.alt_text = altText;
- }
- return params;
-}
+export { fetchInstagramProfile } from './instagramApi.js';
+export { exchangeForLongLivedToken, refreshLongLivedToken, autoRefreshInstagramTokens } from './instagramTokens.js';
+export {
+ classifyInstagramMedia, extractInstagramViews, normalizeInstagramMedia, fetchInstagramMedia,
+} from './instagramMedia.js';
+export { CONTENT_TYPES, summarizeContentTypes } from './instagramContentTypes.js';
+export { computeInstagramAnalytics } from './instagramAnalytics.js';
+export { buildMediaParams } from './instagramPublishing.js';
diff --git a/backend/services/instagramAnalytics.js b/backend/services/instagramAnalytics.js
new file mode 100644
index 0000000..97fa280
--- /dev/null
+++ b/backend/services/instagramAnalytics.js
@@ -0,0 +1,111 @@
+import {
+ sumOf, roundedAverage, medianOf, countWithinDays, postFrequency,
+ consistencyScore, bestToAverageRatio,
+} from './analyticsMath.js';
+import { CONTENT_TYPES, buildContentTypeStats } from './instagramContentTypes.js';
+import { summarizeTiming } from './instagramTiming.js';
+import { buildHashtagAnalysis, buildCaptionLengthCorrelation } from './instagramCaptions.js';
+
+function emptyInstagramAnalytics(profile) {
+ return {
+ totalPosts: profile.mediaCount || 0, fetchedPosts: 0,
+ totalLikes: 0, totalComments: 0, totalEngagement: 0,
+ avgLikes: 0, avgComments: 0, avgEngagement: 0,
+ medianLikes: 0, medianComments: 0,
+ engagementRate: 0, likesPerFollower: 0, commentsPerFollower: 0,
+ totalViews: 0, avgViews: 0, mediaWithViews: 0,
+ bestByLikes: null, bestByComments: null, worstByLikes: null,
+ recentMedia: [], contentTypeStats: buildContentTypeStats([]),
+ postFrequency: { perWeek: 0, perMonth: 0 },
+ topPosts: [],
+ hashtagAnalysis: [], captionLengthCorrelation: [],
+ postsByDayOfWeek: [], postsByHour: [],
+ engagementTimeline: [], monthlyBreakdown: [],
+ postsLast7Days: 0, postsLast30Days: 0, postsLast90Days: 0,
+ viralityScore: 0, consistencyScore: 0,
+ bestPostingDay: '', bestPostingHour: '',
+ likesToCommentsRatio: 0,
+ };
+}
+
+function perFollowerRate(total, postCount, followersCount) {
+ return followersCount > 0 ? parseFloat((total / postCount / followersCount * 100).toFixed(2)) : 0;
+}
+
+function summarizeEngagement(profile, media) {
+ const totalLikes = sumOf(media, item => item.likeCount);
+ const totalComments = sumOf(media, item => item.commentsCount);
+ const totalEngagement = totalLikes + totalComments;
+ return {
+ totalLikes, totalComments, totalEngagement,
+ avgLikes: roundedAverage(totalLikes, media.length),
+ avgComments: roundedAverage(totalComments, media.length),
+ avgEngagement: roundedAverage(totalEngagement, media.length),
+ medianLikes: medianOf(media.map(item => item.likeCount)),
+ medianComments: medianOf(media.map(item => item.commentsCount)),
+ engagementRate: perFollowerRate(totalLikes + totalComments, media.length, profile.followersCount),
+ likesPerFollower: perFollowerRate(totalLikes, media.length, profile.followersCount),
+ commentsPerFollower: perFollowerRate(totalComments, media.length, profile.followersCount),
+ likesToCommentsRatio: totalComments > 0 ? parseFloat((totalLikes / totalComments).toFixed(1)) : 0,
+ };
+}
+
+function summarizeViews(contentTypeStats) {
+ const mediaWithViews = CONTENT_TYPES.reduce((total, type) => total + contentTypeStats[type].viewsReported, 0);
+ const totalViews = CONTENT_TYPES.reduce((total, type) => total + contentTypeStats[type].totalViews, 0);
+ return { totalViews, avgViews: roundedAverage(totalViews, mediaWithViews), mediaWithViews };
+}
+
+function rankByLikesAndComments(media) {
+ const byLikes = [...media].sort((first, second) => second.likeCount - first.likeCount);
+ const byComments = [...media].sort((first, second) => second.commentsCount - first.commentsCount);
+ return {
+ bestByLikes: byLikes[0] || null,
+ bestByComments: byComments[0] || null,
+ worstByLikes: byLikes.length > 0 ? byLikes[byLikes.length - 1] : null,
+ };
+}
+
+function rankTopPosts(media) {
+ return [...media]
+ .map(item => ({ ...item, engagement: item.likeCount + item.commentsCount }))
+ .sort((first, second) => second.engagement - first.engagement)
+ .slice(0, 10);
+}
+
+function countRecentPosts(dates) {
+ const now = Date.now();
+ return {
+ postsLast7Days: countWithinDays(dates, now, 7),
+ postsLast30Days: countWithinDays(dates, now, 30),
+ postsLast90Days: countWithinDays(dates, now, 90),
+ };
+}
+
+export function computeInstagramAnalytics(profile, media) {
+ if (!media || media.length === 0) return emptyInstagramAnalytics(profile);
+
+ const engagement = summarizeEngagement(profile, media);
+ const contentTypeStats = buildContentTypeStats(media);
+ const dates = media.map(item => new Date(item.timestamp)).filter(date => !isNaN(date));
+ const topPosts = rankTopPosts(media);
+ const bestEngagement = topPosts[0] ? topPosts[0].engagement : 0;
+
+ return {
+ totalPosts: profile.mediaCount || media.length,
+ fetchedPosts: media.length,
+ ...engagement,
+ ...summarizeViews(contentTypeStats),
+ ...rankByLikesAndComments(media),
+ recentMedia: media.slice(0, 20),
+ contentTypeStats,
+ postFrequency: postFrequency(dates, media.length),
+ topPosts,
+ ...summarizeTiming(dates, media),
+ ...countRecentPosts(dates),
+ hashtagAnalysis: buildHashtagAnalysis(media),
+ captionLengthCorrelation: buildCaptionLengthCorrelation(media),
+ viralityScore: bestToAverageRatio(bestEngagement, engagement.avgEngagement),
+ consistencyScore: consistencyScore(media.map(item => item.likeCount + item.commentsCount)),
+ };
+}
diff --git a/backend/services/instagramAnalytics.test.js b/backend/services/instagramAnalytics.test.js
new file mode 100644
index 0000000..2ab0eae
--- /dev/null
+++ b/backend/services/instagramAnalytics.test.js
@@ -0,0 +1,41 @@
+process.env.TZ = 'UTC';
+
+import { test, describe, before, after, mock } from 'node:test';
+import { computeInstagramAnalytics } from './instagramAnalytics.js';
+import { assertGolden } from './fixtures/golden.js';
+import { FIXED_NOW, richMedia, zeroEngagementMedia, generatedMedia } from './fixtures/instagramFixtures.js';
+
+describe('computeInstagramAnalytics golden output', () => {
+ before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+ after(() => mock.timers.reset());
+
+ test('empty and missing media return the empty state', () => {
+ assertGolden({
+ empty: computeInstagramAnalytics({ mediaCount: 7 }, []),
+ missing: computeInstagramAnalytics({}, null),
+ }, 'instagramAnalytics.empty');
+ });
+
+ test('a varied account with invalid timestamps and ties', () => {
+ assertGolden(computeInstagramAnalytics({ followersCount: 2500, mediaCount: 140 }, richMedia), 'instagramAnalytics.rich');
+ });
+
+ test('an account without followers or a media count', () => {
+ assertGolden(computeInstagramAnalytics({ followersCount: 0, mediaCount: 0 }, richMedia), 'instagramAnalytics.noFollowers');
+ });
+
+ test('one and two items cover the odd and even medians', () => {
+ assertGolden({
+ single: computeInstagramAnalytics({ followersCount: 10 }, richMedia.slice(0, 1)),
+ pair: computeInstagramAnalytics({ followersCount: 10 }, richMedia.slice(1, 3)),
+ }, 'instagramAnalytics.small');
+ });
+
+ test('media with no engagement at all', () => {
+ assertGolden(computeInstagramAnalytics({ followersCount: 50 }, zeroEngagementMedia), 'instagramAnalytics.zero');
+ });
+
+ test('more than twenty items with many hashtags', () => {
+ assertGolden(computeInstagramAnalytics({ followersCount: 900, mediaCount: 24 }, generatedMedia), 'instagramAnalytics.generated');
+ });
+});
diff --git a/backend/services/instagramApi.js b/backend/services/instagramApi.js
new file mode 100644
index 0000000..1dcd7a1
--- /dev/null
+++ b/backend/services/instagramApi.js
@@ -0,0 +1,68 @@
+// fetch is a global in Cloudflare Workers - no import needed.
+
+const IG_GRAPH_URL = 'https://graph.instagram.com';
+const IG_API_VERSION = 'v25.0';
+const REQUEST_TIMEOUT_MS = 15000;
+const RETRY_DELAY_MS = 1000;
+const UNVERSIONED_PREFIXES = ['/oauth', '/access_token', '/refresh_access_token'];
+
+function buildGraphUrl(endpoint, params) {
+ const needsVersion = !UNVERSIONED_PREFIXES.some(prefix => endpoint.startsWith(prefix));
+ const base = needsVersion ? `${IG_GRAPH_URL}/${IG_API_VERSION}` : IG_GRAPH_URL;
+ const url = new URL(`${base}${endpoint}`);
+ Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
+ return url;
+}
+
+function isTransientError(err) {
+ return err.name === 'AbortError' ||
+ err.message?.includes('EAI_AGAIN') ||
+ err.message?.includes('ECONNRESET');
+}
+
+function readGraphResponse(data) {
+ if (data.error) throw new Error(data.error.message || data.error.error_message || JSON.stringify(data.error));
+ if (data.error_message) throw new Error(data.error_message);
+ return data;
+}
+
+export async function igFetch(endpoint, params = {}, retries = 1) {
+ const url = buildGraphUrl(endpoint, params);
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
+
+ let response;
+ try {
+ response = await fetch(url.toString(), { signal: controller.signal });
+ } catch (err) {
+ clearTimeout(timer);
+ if (isTransientError(err) && retries > 0) {
+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS));
+ return igFetch(endpoint, params, retries - 1);
+ }
+ if (err.name === 'AbortError') throw new Error('Instagram API request timed out');
+ throw new Error(`Instagram API unreachable (${err.message})`);
+ }
+ clearTimeout(timer);
+
+ return readGraphResponse(await response.json());
+}
+
+export async function fetchInstagramProfile(igUserId, accessToken) {
+ const endpoint = igUserId ? `/${igUserId}` : '/me';
+ const data = await igFetch(endpoint, {
+ access_token: accessToken,
+ fields: 'user_id,username,name,profile_picture_url,followers_count,follows_count,media_count,biography,website',
+ });
+ return {
+ igUserId: data.user_id || data.id || igUserId,
+ name: data.name || '',
+ username: data.username || '',
+ profilePictureUrl: data.profile_picture_url || '',
+ followersCount: data.followers_count || 0,
+ followsCount: data.follows_count || 0,
+ mediaCount: data.media_count || 0,
+ biography: data.biography || '',
+ website: data.website || '',
+ };
+}
diff --git a/backend/services/instagramApi.test.js b/backend/services/instagramApi.test.js
new file mode 100644
index 0000000..2734f26
--- /dev/null
+++ b/backend/services/instagramApi.test.js
@@ -0,0 +1,68 @@
+import { test, describe, afterEach } from 'node:test';
+import { fetchInstagramProfile } from './instagramApi.js';
+import { assertGolden } from './fixtures/golden.js';
+import { installFetch, reply } from './fixtures/fakeFetch.js';
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+async function outcomeOf(promise) {
+ try {
+ return { value: await promise };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+function abortError() {
+ const err = new Error('This operation was aborted');
+ err.name = 'AbortError';
+ return err;
+}
+
+describe('fetchInstagramProfile golden output', () => {
+ test('maps a full profile and a sparse one', async () => {
+ const bodies = [
+ { user_id: '1789', id: 'x', username: 'ribbon', name: 'Ribbon', profile_picture_url: 'https://cdn/p.jpg', followers_count: 2500, follows_count: 12, media_count: 140, biography: 'Bio', website: 'https://ribbon.example' },
+ { id: '42' },
+ {},
+ ];
+ fetchMock = installFetch((_request, count) => reply(bodies[count - 1]));
+ const results = [
+ await fetchInstagramProfile('1789', 'TOKEN'),
+ await fetchInstagramProfile(null, 'TOKEN'),
+ await fetchInstagramProfile('555', 'TOKEN'),
+ ];
+ assertGolden({ results, requests: fetchMock.requests }, 'instagramApi.profile');
+ });
+
+ test('turns every Graph API error shape into an Error', async () => {
+ const bodies = [
+ { error: { message: 'Invalid OAuth access token' } },
+ { error: { error_message: 'Legacy message' } },
+ { error: { code: 190 } },
+ { error_message: 'Top-level message' },
+ ];
+ fetchMock = installFetch((_request, count) => reply(bodies[count - 1]));
+ const outcomes = [];
+ for (let i = 0; i < bodies.length; i++) outcomes.push(await outcomeOf(fetchInstagramProfile('1', 'TOKEN')));
+ assertGolden(outcomes, 'instagramApi.errors');
+ });
+
+ test('retries one transient failure and reports network errors', async () => {
+ const script = [
+ abortError(), reply({ id: '7', username: 'retried' }),
+ abortError(), abortError(),
+ new Error('getaddrinfo EAI_AGAIN graph.instagram.com'), new Error('read ECONNRESET'),
+ new Error('certificate expired'),
+ ];
+ fetchMock = installFetch((_request, count) => script[count - 1]);
+ const outcomes = [
+ await outcomeOf(fetchInstagramProfile('7', 'TOKEN')),
+ await outcomeOf(fetchInstagramProfile('7', 'TOKEN')),
+ await outcomeOf(fetchInstagramProfile('7', 'TOKEN')),
+ await outcomeOf(fetchInstagramProfile('7', 'TOKEN')),
+ ];
+ assertGolden({ outcomes, requestCount: fetchMock.requests.length }, 'instagramApi.network');
+ });
+});
diff --git a/backend/services/instagramCaptions.js b/backend/services/instagramCaptions.js
new file mode 100644
index 0000000..17822e9
--- /dev/null
+++ b/backend/services/instagramCaptions.js
@@ -0,0 +1,50 @@
+import { sumOf, roundedAverage } from './analyticsMath.js';
+
+const HASHTAG_PATTERN = /#[\wÀ-ɏ]+/g;
+const MAX_HASHTAGS = 20;
+
+const CAPTION_BUCKETS = [
+ { label: 'No caption', min: 0, max: 0 },
+ { label: 'Short (1-50)', min: 1, max: 50 },
+ { label: 'Medium (51-150)', min: 51, max: 150 },
+ { label: 'Long (151-300)', min: 151, max: 300 },
+ { label: 'Very Long (300+)', min: 301, max: Infinity },
+];
+
+export function buildHashtagAnalysis(media) {
+ const hashtags = {};
+ media.forEach(item => {
+ const found = (item.caption || '').match(HASHTAG_PATTERN) || [];
+ found.forEach(rawTag => {
+ const tag = rawTag.toLowerCase();
+ if (!hashtags[tag]) hashtags[tag] = { tag, count: 0, likes: 0, comments: 0 };
+ hashtags[tag].count++;
+ hashtags[tag].likes += item.likeCount;
+ hashtags[tag].comments += item.commentsCount;
+ });
+ });
+ return Object.values(hashtags)
+ .map(entry => ({ ...entry, avgEngagement: Math.round((entry.likes + entry.comments) / entry.count) }))
+ .sort((first, second) => second.count - first.count)
+ .slice(0, MAX_HASHTAGS);
+}
+
+function summarizeCaptionBucket(bucket, media) {
+ const posts = media.filter(item => {
+ const length = (item.caption || '').length;
+ return length >= bucket.min && length <= bucket.max;
+ });
+ const totalEngagement = posts.reduce((total, item) => total + item.likeCount + item.commentsCount, 0);
+ return {
+ label: bucket.label, count: posts.length,
+ avgLikes: roundedAverage(sumOf(posts, item => item.likeCount), posts.length),
+ avgComments: roundedAverage(sumOf(posts, item => item.commentsCount), posts.length),
+ avgEngagement: roundedAverage(totalEngagement, posts.length),
+ };
+}
+
+export function buildCaptionLengthCorrelation(media) {
+ return CAPTION_BUCKETS
+ .map(bucket => summarizeCaptionBucket(bucket, media))
+ .filter(bucket => bucket.count > 0);
+}
diff --git a/backend/services/instagramContentTypes.js b/backend/services/instagramContentTypes.js
new file mode 100644
index 0000000..bcd2259
--- /dev/null
+++ b/backend/services/instagramContentTypes.js
@@ -0,0 +1,41 @@
+import { roundedAverage } from './analyticsMath.js';
+
+export const CONTENT_TYPES = ['reel', 'post', 'video'];
+
+export function summarizeContentTypes(media) {
+ const summary = {};
+ CONTENT_TYPES.forEach(type => {
+ summary[type] = { count: 0, likes: 0, comments: 0, views: 0, viewsReported: 0 };
+ });
+ (media || []).forEach(item => {
+ const totals = summary[CONTENT_TYPES.includes(item.contentType) ? item.contentType : 'post'];
+ totals.count++;
+ totals.likes += item.likeCount || 0;
+ totals.comments += item.commentsCount || 0;
+ if (typeof item.viewCount === 'number') {
+ totals.views += item.viewCount;
+ totals.viewsReported++;
+ }
+ });
+ return summary;
+}
+
+export function buildContentTypeStats(media) {
+ const summary = summarizeContentTypes(media);
+ const stats = {};
+ CONTENT_TYPES.forEach(type => {
+ const totals = summary[type];
+ stats[type] = {
+ count: totals.count,
+ totalLikes: totals.likes,
+ totalComments: totals.comments,
+ totalViews: totals.views,
+ viewsReported: totals.viewsReported,
+ avgLikes: roundedAverage(totals.likes, totals.count),
+ avgComments: roundedAverage(totals.comments, totals.count),
+ avgEngagement: roundedAverage(totals.likes + totals.comments, totals.count),
+ avgViews: roundedAverage(totals.views, totals.viewsReported),
+ };
+ });
+ return stats;
+}
diff --git a/backend/services/instagramContentTypes.test.js b/backend/services/instagramContentTypes.test.js
new file mode 100644
index 0000000..d7a29e4
--- /dev/null
+++ b/backend/services/instagramContentTypes.test.js
@@ -0,0 +1,21 @@
+import { test, describe } from 'node:test';
+import { CONTENT_TYPES, summarizeContentTypes } from './instagramContentTypes.js';
+import { assertGolden } from './fixtures/golden.js';
+import { richMedia, generatedMedia } from './fixtures/instagramFixtures.js';
+
+describe('summarizeContentTypes golden output', () => {
+ test('summarizes media of every type, unknown types and missing counts', () => {
+ const odd = [
+ { contentType: 'reel', viewCount: '12' },
+ { contentType: undefined, likeCount: 3, commentsCount: null, viewCount: 0 },
+ { contentType: 'video', likeCount: 1, commentsCount: 1, viewCount: NaN },
+ ];
+ assertGolden({
+ types: CONTENT_TYPES,
+ rich: summarizeContentTypes(richMedia),
+ generated: summarizeContentTypes(generatedMedia),
+ odd: summarizeContentTypes(odd),
+ missing: summarizeContentTypes(null),
+ }, 'instagramContentTypes.summary');
+ });
+});
diff --git a/backend/services/instagramMedia.js b/backend/services/instagramMedia.js
new file mode 100644
index 0000000..f4826c8
--- /dev/null
+++ b/backend/services/instagramMedia.js
@@ -0,0 +1,77 @@
+import { igFetch } from './instagramApi.js';
+
+const MEDIA_FIELDS = 'id,caption,media_type,media_product_type,media_url,thumbnail_url,cover_url,permalink,timestamp,like_count,comments_count';
+const VIEWS_FIELD = 'insights.metric(views)';
+const MEDIA_PAGE_SIZE = 50;
+const MAX_MEDIA_PAGES = 10;
+const REEL_PERMALINK = /instagram\.com\/reels?\//i;
+
+// media_type never says REELS; only media_product_type tells a reel from a video
+export function classifyInstagramMedia(raw) {
+ const productType = String(raw?.media_product_type || '').toUpperCase();
+ const mediaType = String(raw?.media_type || '').toUpperCase();
+
+ if (productType === 'REELS') return 'reel';
+ if (!productType && REEL_PERMALINK.test(raw?.permalink || '')) return 'reel';
+ if (mediaType === 'REELS' || mediaType === 'REEL') return 'reel';
+ if (mediaType === 'VIDEO') return 'video';
+ return 'post';
+}
+
+export function extractInstagramViews(raw) {
+ const metric = raw?.insights?.data?.find(insight => insight.name === 'views');
+ const value = metric?.values?.[0]?.value ?? metric?.total_value?.value;
+ const views = Number(value);
+ return value !== undefined && value !== null && Number.isFinite(views) ? views : null;
+}
+
+export function normalizeInstagramMedia(raw) {
+ const contentType = classifyInstagramMedia(raw);
+ const mediaType = String(raw.media_type || 'IMAGE').toUpperCase();
+ return {
+ id: raw.id,
+ caption: raw.caption || '',
+ contentType,
+ mediaType,
+ mediaUrl: raw.media_url || '',
+ thumbnailUrl: raw.cover_url || raw.thumbnail_url || (contentType === 'post' ? raw.media_url || '' : ''),
+ permalink: raw.permalink || '',
+ timestamp: raw.timestamp || '',
+ likeCount: raw.like_count || 0,
+ commentsCount: raw.comments_count || 0,
+ viewCount: extractInstagramViews(raw),
+ };
+}
+
+async function fetchMediaPage(igUserId, accessToken, after) {
+ const params = { access_token: accessToken, limit: String(MEDIA_PAGE_SIZE) };
+ if (after) params.after = after;
+ try {
+ return await igFetch(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` });
+ } catch {
+ // one item without insights (e.g. posted before going professional) fails the whole page
+ return igFetch(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS });
+ }
+}
+
+function uniqueById(items) {
+ const unique = new Map();
+ items.forEach(item => {
+ if (item?.id && !unique.has(item.id)) unique.set(item.id, item);
+ });
+ return [...unique.values()];
+}
+
+export async function fetchInstagramMedia(igUserId, accessToken, limit = 500) {
+ const allMedia = [];
+ let after = null;
+
+ for (let page = 0; page < MAX_MEDIA_PAGES && allMedia.length < limit; page++) {
+ const data = await fetchMediaPage(igUserId, accessToken, after);
+ if (Array.isArray(data.data)) allMedia.push(...data.data);
+ after = data.paging?.next ? data.paging?.cursors?.after : null;
+ if (!after) break;
+ }
+
+ return uniqueById(allMedia).slice(0, limit).map(normalizeInstagramMedia);
+}
diff --git a/backend/services/instagramMedia.test.js b/backend/services/instagramMedia.test.js
new file mode 100644
index 0000000..646fc4b
--- /dev/null
+++ b/backend/services/instagramMedia.test.js
@@ -0,0 +1,51 @@
+import { test, describe, afterEach } from 'node:test';
+import { classifyInstagramMedia, extractInstagramViews, normalizeInstagramMedia, fetchInstagramMedia } from './instagramMedia.js';
+import { assertGolden } from './fixtures/golden.js';
+import { installFetch, reply } from './fixtures/fakeFetch.js';
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+const rawItems = [
+ { id: '1', media_type: 'VIDEO', media_product_type: 'REELS', media_url: 'https://cdn/v.mp4', thumbnail_url: 'https://cdn/t.jpg', cover_url: 'https://cdn/c.jpg', permalink: 'https://www.instagram.com/reel/1/', timestamp: '2026-08-01T10:00:00+0000', like_count: 9, comments_count: 2, caption: 'Reel', insights: { data: [{ name: 'views', values: [{ value: 300 }] }] } },
+ { id: '2', media_type: 'IMAGE', media_url: 'https://cdn/i.jpg' },
+ { id: '3', media_type: 'VIDEO', media_product_type: 'FEED', thumbnail_url: 'https://cdn/t3.jpg', insights: { data: [{ name: 'views', total_value: { value: '41' } }] } },
+ { id: '4', media_type: 'CAROUSEL_ALBUM', insights: { data: [{ name: 'reach', values: [{ value: 5 }] }] } },
+ { id: '5', permalink: 'https://instagram.com/reels/5/', insights: { data: [{ name: 'views', values: [{ value: null }] }] } },
+ { id: '6', media_type: 'reel', insights: { data: [{ name: 'views', values: [{ value: 'Infinity' }] }] } },
+ { id: '7' },
+];
+
+describe('instagram media golden output', () => {
+ test('classifies, reads views and normalizes raw items', () => {
+ assertGolden(rawItems.map(raw => ({
+ type: classifyInstagramMedia(raw),
+ views: extractInstagramViews(raw),
+ normalized: normalizeInstagramMedia(raw),
+ })), 'instagramMedia.normalize');
+ });
+
+ test('pages through media, falls back without insights and dedupes', async () => {
+ fetchMock = installFetch((request) => {
+ const params = new URL(request.url).searchParams;
+ const after = params.get('after') ?? '';
+ if (after === 'p2' && params.get('fields').includes('insights')) return reply({ error: { message: 'insights unavailable' } });
+ if (after === '') return reply({ data: [rawItems[0], rawItems[1], null, { media_type: 'IMAGE' }], paging: { next: 'https://next', cursors: { after: 'p2' } } });
+ if (after === 'p2') return reply({ data: [rawItems[1], rawItems[2]], paging: { next: 'https://next', cursors: { after: 'p3' } } });
+ return reply({ data: [rawItems[3]], paging: { cursors: { after: 'p4' } } });
+ });
+ const media = await fetchInstagramMedia('17841', 'TOKEN');
+ const limited = await fetchInstagramMedia('17841', 'TOKEN', 2);
+ assertGolden({ media, limited, requests: fetchMock.requests }, 'instagramMedia.paging');
+ });
+
+ test('stops after ten pages even when more are offered', async () => {
+ let counter = 0;
+ fetchMock = installFetch(() => {
+ counter++;
+ return reply({ data: [{ id: `p${counter}`, media_type: 'IMAGE' }], paging: { next: 'https://next', cursors: { after: `c${counter}` } } });
+ });
+ const media = await fetchInstagramMedia('17841', 'TOKEN');
+ assertGolden({ ids: media.map(item => item.id), requestCount: fetchMock.requests.length }, 'instagramMedia.pageCap');
+ });
+});
diff --git a/backend/services/instagramPublishing.js b/backend/services/instagramPublishing.js
new file mode 100644
index 0000000..7cb2aa5
--- /dev/null
+++ b/backend/services/instagramPublishing.js
@@ -0,0 +1,71 @@
+function addCarouselParams(params, post) {
+ const { caption, children, collaborators, locationId } = post;
+ params.media_type = 'CAROUSEL';
+ if (caption) params.caption = caption;
+ if (children?.length) params.children = children.join(',');
+ if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);
+ if (locationId) params.location_id = locationId;
+ return params;
+}
+
+function addCarouselImageParams(params, post) {
+ params.image_url = post.mediaUrl;
+ params.is_carousel_item = true;
+ return params;
+}
+
+function addCarouselVideoParams(params, post) {
+ params.media_type = 'VIDEO';
+ params.video_url = post.mediaUrl;
+ params.is_carousel_item = true;
+ return params;
+}
+
+function addReelParams(params, post) {
+ const { mediaUrl, caption, shareToFeed, coverUrl, collaborators, audioName, thumbOffset, locationId, userTags } = post;
+ params.media_type = 'REELS';
+ params.video_url = mediaUrl;
+ if (caption) params.caption = caption;
+ if (shareToFeed !== undefined) params.share_to_feed = shareToFeed;
+ if (coverUrl) params.cover_url = coverUrl;
+ if (collaborators?.length) params.collaborators = JSON.stringify(collaborators);
+ if (audioName) params.audio_name = audioName;
+ if (thumbOffset != null) params.thumb_offset = thumbOffset;
+ if (locationId) params.location_id = locationId;
+ if (userTags?.length) params.user_tags = JSON.stringify(userTags);
+ return params;
+}
+
+function addStoryParams(params, post) {
+ const { mediaUrl, userTags } = post;
+ params.media_type = 'STORIES';
+ if (mediaUrl?.match(/\.(mp4|mov|avi|webm)/i)) {
+ params.video_url = mediaUrl;
+ } else {
+ params.image_url = mediaUrl;
+ }
+ if (userTags?.length) params.user_tags = JSON.stringify(userTags);
+ return params;
+}
+
+function addPhotoParams(params, post) {
+ const { mediaUrl, caption, locationId, userTags, altText } = post;
+ params.image_url = mediaUrl;
+ if (caption) params.caption = caption;
+ if (locationId) params.location_id = locationId;
+ if (userTags?.length) params.user_tags = JSON.stringify(userTags);
+ if (altText) params.alt_text = altText;
+ return params;
+}
+
+// scripts/publish-scheduled.js keeps its own copy because it must stay dependency-free
+export function buildMediaParams(post, accessToken) {
+ const params = { access_token: accessToken };
+ const { mediaType } = post;
+ if (mediaType === 'CAROUSEL') return addCarouselParams(params, post);
+ if (mediaType === 'CAROUSEL_ITEM_IMAGE') return addCarouselImageParams(params, post);
+ if (mediaType === 'CAROUSEL_ITEM_VIDEO') return addCarouselVideoParams(params, post);
+ if (mediaType === 'REELS') return addReelParams(params, post);
+ if (mediaType === 'STORIES') return addStoryParams(params, post);
+ return addPhotoParams(params, post);
+}
diff --git a/backend/services/instagramPublishing.test.js b/backend/services/instagramPublishing.test.js
new file mode 100644
index 0000000..cbc114a
--- /dev/null
+++ b/backend/services/instagramPublishing.test.js
@@ -0,0 +1,45 @@
+import { test, describe } from 'node:test';
+import { buildMediaParams } from './instagramPublishing.js';
+import { assertGolden } from './fixtures/golden.js';
+
+const fullPost = {
+ mediaUrl: 'https://cdn.example/file.jpg',
+ caption: 'Caption #tag',
+ coverUrl: 'https://cdn.example/cover.jpg',
+ shareToFeed: true,
+ collaborators: ['partner_one', 'partner_two'],
+ audioName: 'Original audio',
+ thumbOffset: 1500,
+ locationId: '110',
+ userTags: [{ username: 'friend', x: 0.5, y: 0.5 }],
+ altText: 'A ribbon on a table',
+ children: ['c1', 'c2', 'c3'],
+};
+
+const emptyPost = {
+ mediaUrl: 'https://cdn.example/file.mov',
+ caption: '',
+ collaborators: [],
+ userTags: [],
+ children: [],
+ thumbOffset: null,
+};
+
+const mediaTypes = ['CAROUSEL', 'CAROUSEL_ITEM_IMAGE', 'CAROUSEL_ITEM_VIDEO', 'REELS', 'STORIES', 'IMAGE', undefined];
+
+describe('buildMediaParams golden output', () => {
+ test('builds container parameters for every media type, full and empty', () => {
+ const results = mediaTypes.map(mediaType => ({
+ mediaType: mediaType ?? 'none',
+ full: buildMediaParams({ ...fullPost, mediaType }, 'TOKEN'),
+ empty: buildMediaParams({ ...emptyPost, mediaType }, 'TOKEN'),
+ bare: buildMediaParams({ mediaType }, 'TOKEN'),
+ }));
+ const variants = [
+ buildMediaParams({ mediaType: 'REELS', mediaUrl: 'https://cdn/v.mp4', shareToFeed: false, thumbOffset: 0 }, 'T'),
+ buildMediaParams({ mediaType: 'STORIES', mediaUrl: 'https://cdn/story.WEBM?x=1' }, 'T'),
+ buildMediaParams({ mediaType: 'STORIES', mediaUrl: 'https://cdn/story.avi.jpg' }, 'T'),
+ ];
+ assertGolden({ results, variants }, 'instagramPublishing.params');
+ });
+});
diff --git a/backend/services/instagramTiming.js b/backend/services/instagramTiming.js
new file mode 100644
index 0000000..f11fceb
--- /dev/null
+++ b/backend/services/instagramTiming.js
@@ -0,0 +1,71 @@
+import { DAY_NAMES, roundedAverage, pickHighest, monthKey } from './analyticsMath.js';
+
+function emptyBuckets(size) {
+ return Array(size).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
+}
+
+// dates skips invalid timestamps but is indexed against media; kept to match the stored analytics
+function fillBuckets(buckets, dates, media, bucketIndexOf) {
+ dates.forEach((date, i) => {
+ const bucket = buckets[bucketIndexOf(date)];
+ bucket.count++;
+ bucket.likes += media[i]?.likeCount || 0;
+ bucket.comments += media[i]?.commentsCount || 0;
+ });
+ return buckets;
+}
+
+function buildPostsByDayOfWeek(dates, media) {
+ const buckets = fillBuckets(emptyBuckets(7), dates, media, date => date.getDay());
+ return buckets.map((bucket, i) => ({
+ day: DAY_NAMES[i], shortDay: DAY_NAMES[i].slice(0, 3),
+ posts: bucket.count,
+ avgLikes: roundedAverage(bucket.likes, bucket.count),
+ avgComments: roundedAverage(bucket.comments, bucket.count),
+ avgEngagement: roundedAverage(bucket.likes + bucket.comments, bucket.count),
+ }));
+}
+
+function buildPostsByHour(dates, media) {
+ const buckets = fillBuckets(emptyBuckets(24), dates, media, date => date.getHours());
+ return buckets.map((bucket, i) => ({
+ hour: i, label: `${i}:00`,
+ posts: bucket.count,
+ avgEngagement: roundedAverage(bucket.likes + bucket.comments, bucket.count),
+ }));
+}
+
+function buildMonthlyBreakdown(media) {
+ const months = {};
+ media.forEach(item => {
+ const date = new Date(item.timestamp);
+ if (isNaN(date)) return;
+ const key = monthKey(date);
+ if (!months[key]) months[key] = { posts: 0, likes: 0, comments: 0 };
+ months[key].posts++;
+ months[key].likes += item.likeCount;
+ months[key].comments += item.commentsCount;
+ });
+ return Object.entries(months)
+ .sort(([first], [second]) => first.localeCompare(second))
+ .map(([month, totals]) => ({
+ month, posts: totals.posts,
+ likes: totals.likes, comments: totals.comments,
+ avgLikes: Math.round(totals.likes / totals.posts),
+ avgComments: Math.round(totals.comments / totals.posts),
+ engagement: totals.likes + totals.comments,
+ }));
+}
+
+export function summarizeTiming(dates, media) {
+ const postsByDayOfWeek = buildPostsByDayOfWeek(dates, media);
+ const postsByHour = buildPostsByHour(dates, media);
+ const monthlyBreakdown = buildMonthlyBreakdown(media);
+ const bestDay = pickHighest(postsByDayOfWeek, 'avgEngagement');
+ const bestHour = pickHighest(postsByHour, 'avgEngagement');
+ return {
+ postsByDayOfWeek, bestPostingDay: bestDay?.day || '',
+ postsByHour, bestPostingHour: bestHour?.posts > 0 ? bestHour.label : '',
+ engagementTimeline: monthlyBreakdown, monthlyBreakdown,
+ };
+}
diff --git a/backend/services/instagramTokens.js b/backend/services/instagramTokens.js
new file mode 100644
index 0000000..e0694ce
--- /dev/null
+++ b/backend/services/instagramTokens.js
@@ -0,0 +1,66 @@
+import { getAccounts, updateAccount } from '../lib/db.js';
+import { igFetch } from './instagramApi.js';
+
+const DEFAULT_TOKEN_LIFETIME_S = 5184000;
+const REFRESH_WINDOW_MS = 15 * 24 * 60 * 60 * 1000;
+
+function toTokenResult(data) {
+ return {
+ accessToken: data.access_token,
+ tokenType: data.token_type || 'bearer',
+ expiresIn: data.expires_in || DEFAULT_TOKEN_LIFETIME_S,
+ };
+}
+
+export async function exchangeForLongLivedToken(shortToken, appSecret) {
+ const data = await igFetch('/access_token', {
+ grant_type: 'ig_exchange_token',
+ client_secret: appSecret,
+ access_token: shortToken,
+ });
+ if (!data.access_token) throw new Error('Failed to exchange token - check Instagram App Secret');
+ return toTokenResult(data);
+}
+
+export async function refreshLongLivedToken(longToken) {
+ const data = await igFetch('/refresh_access_token', {
+ grant_type: 'ig_refresh_token',
+ access_token: longToken,
+ });
+ if (!data.access_token) throw new Error('Failed to refresh token');
+ return toTokenResult(data);
+}
+
+function isInstagramWithToken(account) {
+ return account.platform === 'instagram' && account.accessToken && account.tokenExpiresAt;
+}
+
+async function refreshStoredToken(supabase, account) {
+ try {
+ const refreshed = await refreshLongLivedToken(account.accessToken);
+ const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();
+ await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt });
+ console.log(`Token refreshed for @${account.username} - expires ${tokenExpiresAt}`);
+ } catch (err) {
+ console.error(`Failed to refresh token for @${account.username}: ${err.message}`);
+ }
+}
+
+// takes supabase directly because cron handlers have no hono request context
+export async function autoRefreshInstagramTokens(supabase) {
+ try {
+ const accounts = await getAccounts(supabase);
+ const igAccounts = accounts.filter(isInstagramWithToken);
+ if (igAccounts.length === 0) return;
+
+ const soon = new Date(Date.now() + REFRESH_WINDOW_MS);
+ const toRefresh = igAccounts.filter(account => new Date(account.tokenExpiresAt) <= soon);
+ if (toRefresh.length === 0) return;
+
+ for (const account of toRefresh) {
+ await refreshStoredToken(supabase, account);
+ }
+ } catch (err) {
+ console.error('autoRefreshInstagramTokens error:', err.message);
+ }
+}
diff --git a/backend/services/instagramTokens.test.js b/backend/services/instagramTokens.test.js
new file mode 100644
index 0000000..2218bd4
--- /dev/null
+++ b/backend/services/instagramTokens.test.js
@@ -0,0 +1,91 @@
+import { test, describe, before, after, afterEach, mock } from 'node:test';
+import { exchangeForLongLivedToken, refreshLongLivedToken, autoRefreshInstagramTokens } from './instagramTokens.js';
+import { assertGolden } from './fixtures/golden.js';
+import { installFetch, reply } from './fixtures/fakeFetch.js';
+import { fakeSupabase, accountRow } from './fixtures/fakeSupabase.js';
+import { FIXED_NOW } from './fixtures/instagramFixtures.js';
+
+const DAY_MS = 86400000;
+let fetchMock = null;
+
+before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+after(() => mock.timers.reset());
+afterEach(() => {
+ fetchMock?.restore();
+ mock.restoreAll();
+});
+
+async function outcomeOf(promise) {
+ try {
+ return { value: await promise };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+function captureConsole() {
+ const lines = [];
+ mock.method(console, 'log', (...args) => lines.push(['log', ...args]));
+ mock.method(console, 'error', (...args) => lines.push(['error', ...args]));
+ return lines;
+}
+
+function expiresIn(days) {
+ return new Date(FIXED_NOW + days * DAY_MS).toISOString();
+}
+
+describe('token exchange and refresh golden output', () => {
+ test('exchange and refresh map the response and reject a missing token', async () => {
+ const bodies = [
+ { access_token: 'LONG', token_type: 'Bearer', expires_in: 3600 },
+ { access_token: 'LONG2' },
+ { token_type: 'bearer' },
+ { access_token: 'REFRESHED', expires_in: 7200 },
+ { access_token: 'REFRESHED2' },
+ {},
+ ];
+ fetchMock = installFetch((_request, count) => reply(bodies[count - 1]));
+ const outcomes = [
+ await outcomeOf(exchangeForLongLivedToken('SHORT', 'SECRET')),
+ await outcomeOf(exchangeForLongLivedToken('SHORT', 'SECRET')),
+ await outcomeOf(exchangeForLongLivedToken('SHORT', 'SECRET')),
+ await outcomeOf(refreshLongLivedToken('LONG')),
+ await outcomeOf(refreshLongLivedToken('LONG')),
+ await outcomeOf(refreshLongLivedToken('LONG')),
+ ];
+ assertGolden({ outcomes, requests: fetchMock.requests }, 'instagramTokens.exchange');
+ });
+});
+
+describe('autoRefreshInstagramTokens golden output', () => {
+ test('refreshes only tokens that expire within fifteen days and logs each result', async () => {
+ const supabase = fakeSupabase([
+ accountRow({ id: 'a1', platform: 'instagram', username: 'soon', accessToken: 'T1', tokenExpiresAt: expiresIn(5) }),
+ accountRow({ id: 'a2', platform: 'instagram', username: 'later', accessToken: 'T2', tokenExpiresAt: expiresIn(40) }),
+ accountRow({ id: 'a3', platform: 'instagram', username: 'notoken', tokenExpiresAt: expiresIn(1) }),
+ accountRow({ id: 'a4', platform: 'instagram', username: 'noexpiry', accessToken: 'T4' }),
+ accountRow({ id: 'a5', platform: 'youtube', channelId: 'UC1', accessToken: 'T5', tokenExpiresAt: expiresIn(1) }),
+ accountRow({ id: 'a6', platform: 'instagram', username: 'failing', accessToken: 'T6', tokenExpiresAt: expiresIn(15) }),
+ accountRow({ id: 'a7', platform: 'instagram', username: 'expired', accessToken: 'T7', tokenExpiresAt: expiresIn(-2) }, 'user-2'),
+ ]);
+ const bodies = {
+ T1: { access_token: 'N1', expires_in: 5184000 },
+ T6: { error: { message: 'Session has expired' } },
+ T7: { access_token: 'N7' },
+ };
+ fetchMock = installFetch((request) => reply(bodies[new URL(request.url).searchParams.get('access_token')]));
+ const lines = captureConsole();
+ await autoRefreshInstagramTokens(supabase);
+ assertGolden({ lines, requests: fetchMock.requests, calls: supabase.calls, table: supabase.table }, 'instagramTokens.autoRefresh');
+ });
+
+ test('does nothing without due accounts and logs a failed account lookup', async () => {
+ fetchMock = installFetch(() => reply({}));
+ const lines = captureConsole();
+ const notDue = fakeSupabase([accountRow({ id: 'b1', platform: 'instagram', accessToken: 'T', tokenExpiresAt: expiresIn(30) })]);
+ await autoRefreshInstagramTokens(notDue);
+ await autoRefreshInstagramTokens(fakeSupabase([]));
+ await autoRefreshInstagramTokens({ from() { throw new Error('database unavailable'); } });
+ assertGolden({ lines, requests: fetchMock.requests, calls: notDue.calls }, 'instagramTokens.idle');
+ });
+});
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 2cf60f3..9d9b5a9 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -2,42 +2,42 @@
Services in `backend/services/` contain all logic for communicating with external APIs (YouTube, Instagram) and computing analytics. Route handlers call services; services never import from routes.
-## `backend/services/instagram.js`
+## Shared analytics math (`backend/services/analyticsMath.js`)
-### HTTP Client
+Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest` and `monthKey` (local time). YouTube keeps its own recency (strict `<`) and weekly consistency formulas and only shares `monthKey`.
-All Instagram Graph API calls go through `igFetch(path, token, options)`:
+---
-```js
-async function igFetch(path, token, options = {}) {
- const url = `https://graph.instagram.com/v25.0${path}`;
- const res = await fetch(url, {
- headers: { Authorization: `Bearer ${token}` },
- ...options,
- });
- const data = await res.json();
- if (data.error) throw new Error(data.error.message);
- return data;
-}
-```
+## Instagram (`backend/services/instagram*.js`)
+
+`services/instagram.js` is a barrel that re-exports the public names below, so routes, the scheduler and tests import from it unchanged. Each module imports its siblings directly, never the barrel.
+
+| Module | Contents |
+|---|---|
+| `instagramApi.js` | `igFetch(endpoint, params, retries)` transport (15 s timeout, one retry on abort, `EAI_AGAIN` or `ECONNRESET`, no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`) and `fetchInstagramProfile` |
+| `instagramTokens.js` | `exchangeForLongLivedToken`, `refreshLongLivedToken`, `autoRefreshInstagramTokens` |
+| `instagramMedia.js` | `classifyInstagramMedia`, `extractInstagramViews`, `normalizeInstagramMedia`, paged `fetchInstagramMedia` |
+| `instagramContentTypes.js` | `CONTENT_TYPES`, `summarizeContentTypes`, per type stats used by the analytics |
+| `instagramTiming.js` | Posts by day of week and hour, best posting day and hour, monthly breakdown |
+| `instagramCaptions.js` | Hashtag analysis and caption length correlation |
+| `instagramAnalytics.js` | `computeInstagramAnalytics` orchestrator, the empty state and the engagement, views and ranking helpers |
+| `instagramPublishing.js` | `buildMediaParams`, one helper per media type |
### Key Functions
| Function | Purpose |
|---|---|
-| `exchangeCodeForToken(code, env)` | Short-lived code -> short-lived token (Instagram OAuth step 1) |
-| `exchangeForLongLivedToken(shortToken, env)` | Short-lived -> 60-day long-lived token (Instagram OAuth step 2) |
-| `getIGProfile(accessToken)` | Fetches `id, username, account_type, media_count` for the token |
+| `fetchInstagramProfile(igUserId, accessToken)` | Fetches the profile for an account id, or for `/me` when `igUserId` is null |
+| `exchangeForLongLivedToken(shortToken, appSecret)` | Short-lived -> 60-day long-lived token |
+| `refreshLongLivedToken(accessToken)` | Extends a long-lived token; call before expiry |
+| `autoRefreshInstagramTokens(supabase)` | Cron handler - refreshes all tokens expiring within 15 days |
| `fetchInstagramMedia(igUserId, accessToken, limit)` | Paginates media (50 per page, 10 pages max) up to `limit` (default 500), requesting `views` insights inline; returns normalized items |
| `classifyInstagramMedia(raw)` | Returns `'reel'`, `'post'`, or `'video'` for a raw Graph API media item |
| `extractInstagramViews(raw)` | Reads the `views` insight from a raw item; `null` when Instagram reports none |
| `normalizeInstagramMedia(raw)` | Maps a raw item to the cached media shape (`contentType`, `viewCount`, counts, URLs) |
| `summarizeContentTypes(media)` | Per content type `{ count, likes, comments, views, viewsReported }`; always returns all three types |
-| `refreshLongLivedToken(accessToken)` | Extends a long-lived token; call before expiry |
-| `autoRefreshInstagramTokens(supabase)` | Cron handler - refreshes all tokens expiring within 15 days |
| `computeInstagramAnalytics(profile, media)` | Computes engagement rates, views, per-content-type stats, hashtag analysis, timing patterns, monthly breakdown |
-| `publishIGContainer(igUserId, params, token)` | Creates a media container via Graph API |
-| `publishIGMedia(igUserId, containerId, token)` | Publishes a container; returns `mediaId` |
+| `buildMediaParams(post, accessToken)` | Graph API container parameters for one media item |
### Content type classification
@@ -108,7 +108,7 @@ async function ytFetch(path, params, env) {
- Monthly breakdown of uploads and views
- Category distribution
-`computeInstagramAnalytics()` (in `instagram.js`) returns:
+`computeInstagramAnalytics()` (in `instagramAnalytics.js`) returns:
- Engagement rate (likes + comments / followers)
- Average likes, comments per post
- Best performing post
@@ -146,7 +146,7 @@ Reddit integration requires no Worker secrets. The session cookie is a per-user
## Shared Instagram publishing parameters
-`buildMediaParams(post, accessToken)` in `services/instagram.js` builds the Graph API container parameters for photos, Reels, Stories and carousel items. The publish route (`routes/publishing.js`) and the cron scheduler (`utils/scheduler.js`) both call it. `scripts/publish-scheduled.js` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.
+`buildMediaParams(post, accessToken)` in `services/instagramPublishing.js` (re-exported by `services/instagram.js`) builds the Graph API container parameters for photos, Reels, Stories and carousel items. The publish route (`routes/publishing.js`) and the cron scheduler (`utils/scheduler.js`) both call it. `scripts/publish-scheduled.js` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.
---