export default {
  async scheduled(event, env, ctx) {
    ctx.waitUntil(runFetchCycle(env));
  },

  async fetch(request, env) {
    return new Response("OK");
  }
};

// Analysts by user ID → username (for display)
const ANALYSTS = {
  "1056178693385711617": "smashelito",
  "15884435":            "julie_wade",
  "1430587844372873221": "vighnaraj2022",
  "1452973979363328005": "lonelyRaph",
  "1375113000521203716": "realjc",
  "59117354":            "verniman"
};

// Keyword filters per analyst — post must contain at least one keyword to pass
const ANALYST_FILTERS = {
  "1056178693385711617": ["$BLANK"],
  "15884435":            ["$ES", "$ES_F", "#ES_F", "#ES", "$VIX", "$SPX", "Monthly", "Daily", "VIX", "GEX"],
  "1430587844372873221": ["$SPX", "$VIX", "VIX", "SPX"],
  "1452973979363328005": ["#SPX", "$SPX", "#ES", "#ES_F", "$ES", "$ES_F"],
  "1375113000521203716": ["SPX"],
  "59117354":            ["#ES_F"]
};

function passesFilter(userId, text) {
  const filters = ANALYST_FILTERS[userId];
  if (!filters) return true;
  const lower = text.toLowerCase();
  return filters.some(kw => lower.includes(kw.toLowerCase()));
}

function assertEnv(env) {
  const required = ["X_BEARER_TOKEN", "TELEGRAM_BOT_TOKEN", "TELEGRAM_CHANNEL_ID"];
  for (const key of required) {
    if (!env[key]) throw new Error(`Missing env var: ${key}`);
  }
}

async function runFetchCycle(env) {
  try {
    assertEnv(env);
  } catch (e) {
    console.log("ENV ERROR:", e.message);
    return;
  }

  console.log("[WorkerA] Starting fetch cycle at", new Date().toISOString());

  let seen;
  try {
    seen = await loadCache(env);
  } catch (e) {
    console.log("[WorkerA] KV loadCache failed, starting with empty cache:", e);
    seen = new Set();
  }

  let newPosts = [];

  for (const [userId, username] of Object.entries(ANALYSTS)) {
    try {
      const posts = await fetchUserTimeline(userId, username, seen, env);
      if (posts.length > 0) {
        console.log(`[WorkerA] ${username} → ${posts.length} new posts`);
      }
      newPosts = newPosts.concat(posts);
    } catch (e) {
      console.log(`[WorkerA] fetchUserTimeline failed for ${username}:`, e);
    }
  }

  if (newPosts.length > 0) {
    try {
      await sendToTelegram(newPosts, env);
    } catch (e) {
      console.log("[WorkerA] sendToTelegram failed:", e);
    }

    try {
      await env.ANALYST_POSTS_KV.put("latest_posts", JSON.stringify({
        timestamp: new Date().toISOString(),
        posts: newPosts
      }));
    } catch (e) {
      console.log("[WorkerA] KV put latest_posts failed:", e);
    }
  } else {
    console.log("[WorkerA] No new posts this cycle.");
  }

  try {
    await saveCache(seen, env);
  } catch (e) {
    console.log("[WorkerA] KV saveCache failed:", e);
  }

  console.log("[WorkerA] Fetch cycle complete.");
}

async function loadCache(env) {
  const raw = await env.ANALYST_POSTS_KV.get("processed_ids");
  return raw ? new Set(JSON.parse(raw)) : new Set();
}

async function saveCache(seen, env) {
  const arr = Array.from(seen).slice(-2000);
  await env.ANALYST_POSTS_KV.put("processed_ids", JSON.stringify(arr));
}

function escapeMD(text) {
  if (!text) return "";
  return text.replace(/([_*\[\]()~`>#+\-=|{}.!])/g, "\\$1");
}

async function safeGet(url, params, env, retries = 3) {
  const qs = new URLSearchParams(params).toString();
  for (let i = 0; i < retries; i++) {
    const res = await fetch(`${url}?${qs}`, {
      headers: { Authorization: `Bearer ${env.X_BEARER_TOKEN}` }
    });
    if (res.ok) return res;
    const status = res.status;
    const body = await res.text().catch(() => "");
    console.log(`[WorkerA] X API error ${status}, attempt ${i + 1}, body: ${body}`);
    if (status === 429) {
      await sleep(2000 * (i + 1));
    } else {
      await sleep(500 * (i + 1));
    }
  }
  return null;
}

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}

async function fetchUserTimeline(userId, username, seen, env) {
  const params = {
    max_results: 10,
    "tweet.fields": "created_at,text,attachments",
    expansions: "attachments.media_keys",
    "media.fields": "url,preview_image_url,type",
    exclude: "retweets,replies"
  };

  const res = await safeGet(
    `https://api.twitter.com/2/users/${userId}/tweets`,
    params,
    env
  );

  if (!res) {
    console.log(`[WorkerA] X fetch failed for ${username}`);
    return [];
  }

  const data = await res.json();
  if (!data.data) return [];

  const mediaMap = {};
  (data.includes?.media || []).forEach(m => mediaMap[m.media_key] = m);

  const posts = [];

  for (const t of data.data) {
    if (seen.has(t.id)) continue;

    if (!passesFilter(userId, t.text)) {
      seen.add(t.id);
      continue;
    }

    const post = {
      id: t.id,
      url: `https://x.com/${username}/status/${t.id}`,
      text: t.text,
      time: t.created_at,
      user: username,
      media_urls: []
    };

    if (t.attachments?.media_keys) {
      for (const key of t.attachments.media_keys) {
        const m = mediaMap[key];
        if (m?.type === "photo") {
          const u = m.url || m.preview_image_url;
          if (u) post.media_urls.push(u);
        }
      }
    }

    posts.push(post);
    seen.add(t.id);
  }

  return posts;
}

async function sendToTelegram(posts, env) {
  for (const post of posts) {
    const caption =
      `@${escapeMD(post.user)} • ${escapeMD(post.time)}\n` +
      `${escapeMD(post.text)}\n` +
      `${escapeMD(post.url)}`;

    if (post.media_urls.length === 0) {
      try {
        const res = await telegramSend(env, {
          method: "sendMessage",
          chat_id: env.TELEGRAM_CHANNEL_ID,
          text: caption,
          parse_mode: "MarkdownV2",
          disable_web_page_preview: true
        });
        if (!res.ok) {
          console.log("[WorkerA] Telegram sendMessage failed:", res.status, await res.text());
        } else {
          console.log("[WorkerA] Sent text-only post", post.url);
        }
      } catch (e) {
        console.log("[WorkerA] Telegram sendMessage threw:", e);
      }
      continue;
    }

    const media = post.media_urls.slice(0, 10).map((url, i) => ({
      type: "photo",
      media: url,
      caption: i === 0 ? caption : undefined,
      parse_mode: "MarkdownV2"
    }));

    try {
      const res = await telegramSend(env, {
        method: "sendMediaGroup",
        chat_id: env.TELEGRAM_CHANNEL_ID,
        media
      });

      if (!res.ok) {
        console.log("[WorkerA] Telegram sendMediaGroup failed:", res.status, await res.text());
        const fallback = await telegramSend(env, {
          method: "sendMessage",
          chat_id: env.TELEGRAM_CHANNEL_ID,
          text: caption + "\n(Images failed)",
          parse_mode: "MarkdownV2"
        });
        if (!fallback.ok) {
          console.log("[WorkerA] Telegram fallback failed:", fallback.status, await fallback.text());
        }
      } else {
        console.log("[WorkerA] Sent media post", post.url, "with", media.length, "images");
      }
    } catch (e) {
      console.log("[WorkerA] Telegram sendMediaGroup threw:", e);
      try {
        await telegramSend(env, {
          method: "sendMessage",
          chat_id: env.TELEGRAM_CHANNEL_ID,
          text: caption + "\n(Images failed)",
          parse_mode: "MarkdownV2"
        });
      } catch (e2) {
        console.log("[WorkerA] Telegram fallback threw:", e2);
      }
    }
  }
}

async function telegramSend(env, payload) {
  const { method = "sendMessage", ...body } = payload;
  return fetch(`https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
}