#!/usr/bin/env node
/**
 * CLI for the persistent trend store (research-engine §5, foundation layer).
 *
 *   node --import tsx src/cli.ts add   --title "<t>" --url "<u>" --topics <a,b>
 *                                       [--source <s>] [--summary "<s>"] [--store <path>]
 *   node --import tsx src/cli.ts query --topics <a,b>  [--store <path>] [--json]
 *   node --import tsx src/cli.ts list   [--since <YYYY-MM-DD>] [--limit <n>] [--store <path>] [--json]
 *
 * The capture agent (research-engine) calls `add` to fold a freshly-polled trend
 * into the store, and `query`/`list` to reason over accumulated history. The
 * polling + relevance-scoring itself lives upstream; this is the deterministic store.
 *
 * Exit code: 0 on success, 2 on usage error.
 */

import {
  addTrend,
  defaultStorePath,
  history,
  loadStore,
  queryByTopic,
  saveStore,
} from "./store.js";

function parseFlags(args: string[]): Record<string, string> {
  const out: Record<string, string> = {};
  for (let i = 0; i < args.length; i++) {
    const a = args[i];
    if (a.startsWith("--")) {
      const key = a.slice(2);
      const next = args[i + 1];
      if (next === undefined || next.startsWith("--")) {
        out[key] = "true";
      } else {
        out[key] = next;
        i++;
      }
    }
  }
  return out;
}

function splitTopics(raw: string | undefined): string[] {
  if (!raw) return [];
  return raw
    .split(",")
    .map((t) => t.trim())
    .filter((t) => t.length > 0);
}

function usage(msg: string): never {
  console.error(`error: ${msg}`);
  console.error(
    "usage:\n" +
      '  add --title "<t>" --url "<u>" --topics <a,b> [--source <s>] [--summary "<s>"] [--store <path>]\n' +
      "  query --topics <a,b> [--store <path>] [--json]\n" +
      "  list [--since <YYYY-MM-DD>] [--limit <n>] [--store <path>] [--json]",
  );
  process.exit(2);
}

function today(): string {
  return new Date().toISOString().slice(0, 10);
}

function main(): void {
  const [command, ...rest] = process.argv.slice(2);
  const flags = parseFlags(rest);
  const storePath = flags.store ?? defaultStorePath();
  const asJson = flags.json === "true";

  if (command === "add") {
    const title = flags.title;
    if (!title || title === "true") usage('add needs --title "<text>"');
    const url = flags.url;
    if (!url || url === "true") usage('add needs --url "<url>"');
    const topics = splitTopics(flags.topics);
    if (topics.length === 0) usage("add needs --topics <a,b>");
    const store = loadStore(storePath);
    const res = addTrend(store, {
      title,
      url,
      source: flags.source && flags.source !== "true" ? flags.source : "manual",
      capturedAt: today(),
      topics,
      ...(flags.summary && flags.summary !== "true" ? { summary: flags.summary } : {}),
    });
    saveStore(storePath, res.store);
    if (res.added) {
      console.log(`Added: ${title}`);
    } else {
      console.log(`Duplicate — already in store${res.merged ? " (topics unioned)" : ""}: ${title}`);
    }
    console.log(`Store: ${storePath} (${res.store.trends.length} trends)`);
    return;
  }

  if (command === "query") {
    const topics = splitTopics(flags.topics);
    if (topics.length === 0) usage("query needs --topics <a,b>");
    const hits = queryByTopic(loadStore(storePath), topics);
    if (asJson) {
      console.log(JSON.stringify(hits, null, 2));
      return;
    }
    if (hits.length === 0) {
      console.log(`No trends found for topics: ${topics.join(", ")}`);
      console.log("→ poll fresh signals (research engine), then `add` them.");
      return;
    }
    console.log(`${hits.length} trend(s) for: ${topics.join(", ")}`);
    for (const { trend, topicOverlap } of hits) {
      console.log(`\n  · (overlap ${topicOverlap}) ${trend.title}`);
      console.log(`    ${trend.url}`);
      console.log(`    topics: ${trend.topics.join(", ")} — ${trend.source}, ${trend.capturedAt}`);
      if (trend.summary) console.log(`    ${trend.summary}`);
    }
    return;
  }

  if (command === "list") {
    const opts: { since?: string; limit?: number } = {};
    if (flags.since && flags.since !== "true") opts.since = flags.since;
    if (flags.limit && flags.limit !== "true") {
      const n = Number.parseInt(flags.limit, 10);
      if (Number.isNaN(n) || n < 0) usage("--limit must be a non-negative integer");
      opts.limit = n;
    }
    const rows = history(loadStore(storePath), opts);
    if (asJson) {
      console.log(JSON.stringify(rows, null, 2));
      return;
    }
    const scope = opts.since ? ` since ${opts.since}` : "";
    console.log(`Store: ${storePath} — ${rows.length} trend(s)${scope}`);
    for (const t of rows) {
      console.log(`  · ${t.capturedAt}  ${t.title}  {${t.topics.join(", ")}}`);
    }
    return;
  }

  usage(command ? `unknown command: ${command}` : "no command given");
}

main();
