// sarah-name: Transit Times
// sarah-version: 1.0.0
// sarah-description: Station lookup via Nominatim; live times need API key.
// sarah-category: Web & Data
manifest = {
  name: "Transit Times",
  version: "1.0.0",
  description: "Station lookup + live departure setup guide",
  commands: [
    { id: "lookup", title: "Find station/stop", tool: "transit_lookup" },
    { id: "setup", title: "Live departures setup", tool: "transit_setup" },
  ],
};
tools = [
  {
    name: "transit_lookup",
    description: "Find nearest station/stop coords via OpenStreetMap Nominatim (free, no key)",
    parameters: {
      type: "object",
      properties: {
        city: { type: "string", description: "City name" },
        mode: { type: "string", description: "rail, bus, tram or all (default all)" },
      },
      required: ["city"],
    },
    run: async (args, sarah) => {
      const mode = (args.mode || "all").toLowerCase();
      const label = mode === "all" ? "station" : mode + " station";
      const q = encodeURIComponent(`${label} ${args.city}`);
      const url = `https://nominatim.openstreetmap.org/search?format=json&limit=5&q=${q}`;
      const r = await sarah.shell.run(`curl -s --max-time 15 -A 'SARAH/1.0' ${JSON.stringify(url)}`);
      if (r.code !== 0) throw new Error("Nominatim unreachable");
      let d;
      try { d = JSON.parse(r.stdout); } catch { throw new Error("Nominatim returned bad data"); }
      if (!d.length) return "No stations found near: " + args.city;
      const lines = d.map((p, i) => {
        const short = p.display_name.split(",").slice(0, 3).join(", ");
        return `${i + 1}. ${short}\n   lat ${p.lat}, lon ${p.lon}`;
      });
      return `Stations near ${args.city} (${mode}):\n${lines.join("\n")}\n\nNOTE: live departures need a local API key — run transit_setup.`;
    },
  },
  {
    name: "transit_setup",
    description: "Setup guide for live departures; saves provider key via sarah.store",
    parameters: {
      type: "object",
      properties: {
        key: { type: "string", description: "Optional: save your TransportAPI key" },
        provider: { type: "string", description: "Provider name, default transportapi" },
      },
    },
    run: async (args, sarah) => {
      const prov = args.provider || "transportapi";
      if (args.key) {
        await sarah.store.set(`transit_${prov}_key`, args.key);
        await sarah.ui.notify("Transit key saved");
        return "API key saved. Use provider docs for live boards.";
      }
      const saved = await sarah.store.get("transit_transportapi_key");
      return [
        "Live departures need a local key (no global free API).",
        "UK: TransportAPI (transportapi.com) app_id+app_key.",
        "US: 511 / GTFS-RT agency feeds; DE: Deutsche Bahn API.",
        saved ? "Status: key IS saved." : "Status: no key saved — call transit_setup with {key} to save.",
      ].join("\n");
    },
  },
];
