import { OwnPostPerformanceItem, PostPerformance, PublishHealth } from "../api/haixun";

const DAY_MS = 24 * 60 * 60 * 1000;

export function parsePostTimestamp(value?: string): number | null {
  const raw = (value || "").trim();
  if (!raw) return null;
  const ms = Date.parse(raw);
  return Number.isFinite(ms) ? ms : null;
}

export function postsWithinDays(posts: OwnPostPerformanceItem[], days: number, now = Date.now()): OwnPostPerformanceItem[] {
  const cutoff = now - days * DAY_MS;
  return posts.filter((post) => {
    const ts = parsePostTimestamp(post.timestamp);
    return ts !== null && ts >= cutoff;
  });
}

export type PostEngagement7d = {
  postCount: number;
  likes: number;
  replies: number;
  views: number;
};

/** Sum engagement for Threads API posts published within the last N days. */
export function engagementFromPosts(posts: OwnPostPerformanceItem[], days = 7, now = Date.now()): PostEngagement7d {
  const recent = postsWithinDays(posts, days, now);
  return {
    postCount: recent.length,
    likes: recent.reduce((sum, post) => sum + post.like_count, 0),
    replies: recent.reduce((sum, post) => sum + post.reply_count, 0),
    views: recent.reduce((sum, post) => sum + (post.views ?? 0), 0)
  };
}

export type QueueHealth7d = {
  postCount: number;
  likes: number;
  replies: number;
};

/** Metrics from publish-health: only posts sent through this app's queue. */
export function engagementFromQueueHealth(health?: PublishHealth): QueueHealth7d {
  return {
    postCount: health?.summary.published_7d ?? 0,
    likes: health?.summary.total_likes_7d ?? 0,
    replies: health?.summary.total_replies_7d ?? 0
  };
}

export function buildPublishPageStats(performance?: PostPerformance, health?: PublishHealth) {
  const api7d = engagementFromPosts(performance?.posts || [], 7);
  const queue7d = engagementFromQueueHealth(health);
  const useApi = api7d.postCount > 0 || queue7d.postCount === 0;
  const primary = useApi ? api7d : { ...queue7d, views: 0, postCount: queue7d.postCount };
  const source = useApi ? "threads_api" : "publish_queue";
  return {
    source,
    postCount7d: primary.postCount,
    likes7d: primary.likes,
    replies7d: primary.replies,
    views7d: "views" in primary ? primary.views : 0,
    interactions7d: primary.likes + primary.replies,
    api7d,
    queue7d
  };
}