import "./dotenv.js"; // Must be first - loads .env before other imports
import { getCursor, setCursor, db } from "./db.js";
import { Jetstream } from "./jetstream.js";
import { handleEvent, COLLECTIONS } from "./handler.js";

const JETSTREAM_URL =
  process.env.JETSTREAM_URL || "wss://jetstream2.us-east.bsky.network/subscribe";

async function main() {
  console.log("Sidetrail Ingester starting...");

  if (!process.env.DATABASE_URL) {
    console.error("ERROR: DATABASE_URL environment variable is required");
    process.exit(1);
  }

  // Get cursor for resumable ingestion
  const cursor = await getCursor();
  console.log(`Starting from cursor: ${cursor ?? "beginning"}`);

  // Create Jetstream connection
  const jetstream = new Jetstream({
    instanceUrl: JETSTREAM_URL,
    wantedCollections: COLLECTIONS,
    cursor,
    setCursor,
    onEvent: async (evt) => {
      const { commit } = evt as { commit?: { collection: string; operation: string } };
      if (commit) {
        console.log(`${commit.operation.toUpperCase()} ${commit.collection}`);
      }
      await handleEvent(db, evt);
    },
    onError: (err) => {
      console.error("Jetstream error:", err);
    },
  });

  // Handle graceful shutdown
  process.on("SIGINT", () => {
    console.log("Shutting down...");
    jetstream.destroy();
    process.exit(0);
  });

  process.on("SIGTERM", () => {
    console.log("Shutting down...");
    jetstream.destroy();
    process.exit(0);
  });

  // Start listening
  jetstream.start();
  console.log(`Listening for: ${COLLECTIONS.join(", ")}`);
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
