import assert from "node:assert/strict";
import test from "node:test";
import type { AgentConfig } from "../src/config.js";
import { extractTrendCandidates, researchTrends } from "../src/providers/xapi.js";

test("xAPI tweet responses become ranked candidates from real hashtags", () => {
  const candidates = extractTrendCandidates({
    data: {
      tweets: [
        { tweet_id: "1", text: "Watching #Alpha", favorite_count: 10, retweet_count: 2 },
        { tweet_id: "2", text: "#Beta and #Alpha are moving", favorite_count: 20, retweet_count: 4 },
        { tweet_id: "3", text: "No tag but still real source text", favorite_count: 1 },
      ],
    },
  }, 3);

  assert.equal(candidates[0]?.name, "#Alpha");
  assert.equal(candidates[0]?.volume, 2);
  assert.equal(candidates[0]?.url, "https://x.com/i/web/status/1");
  assert.equal(candidates[1]?.name, "#Beta");
  assert.equal(candidates[2]?.name, "No tag but still real source text");
});

test("unrecognized xAPI responses do not fabricate candidates", () => {
  assert.deepEqual(extractTrendCandidates({ data: { users: [] } }, 5), []);
});

test("one failed research candidate does not abort the entire scan", async (context) => {
  context.mock.method(globalThis, "fetch", async (_url, init) => {
    const request = JSON.parse(String(init?.body)) as { input: { raw_query: string } };
    if (request.input.raw_query === "#Broken") {
      return new Response(JSON.stringify({ code: "INVALID_INPUT" }), { status: 400 });
    }
    return new Response(JSON.stringify({ data: { tweets: [{ tweet_id: "1", text: "#Alpha" }] } }), { status: 201 });
  });

  const config = {
    xApi: { baseUrl: "https://action.xapi.to", key: "test-key", query: "crypto", location: "worldwide" },
  } as AgentConfig;
  const research = await researchTrends(config, [
    { name: "#Alpha", rank: 1 },
    { name: "#Broken", rank: 2 },
  ]);

  assert.equal(research.length, 1);
  assert.equal(research[0]?.name, "#Alpha");
});
