import { Command } from "commander";
import { closePool } from "./db.js";
import { ingestHttp, ingestImage, ingestText, ingestProfile } from "./lib/ingest/index.js";
import type { MediaType, ContentType, TextLang } from "./types.js";

const program = new Command();

program
  .name("ingest")
  .description("OSINT data ingestion CLI")
  .requiredOption("--type <type>", "Data type: http | image | screenshot | text | profile")
  .option("--file <path>", "File path to ingest")
  .option("--entity-id <id>", "Associated entity FB ID")
  .option("--content-id <id>", "Associated content ID")
  .option("--text <content>", "Text content (for --type text)")
  .option("--lang <code>", "Language code (ar/en)")
  .option("--note <text>", "Analyst note")
  .option(
    "--investigation <id>",
    "Investigation ID",
    process.env.INVESTIGATION_ID ?? "default",
  );

interface Opts {
  type: string;
  file?: string;
  entityId?: string;
  contentId?: string;
  text?: string;
  lang?: string;
  note?: string;
  investigation: string;
}

async function run(): Promise<void> {
  program.parse();
  const opts = program.opts<Opts>();
  const inv = opts.investigation;

  switch (opts.type) {
    case "http":
      if (!opts.file) throw new Error("--file is required for --type http");
      await ingestHttp(opts.file, inv, opts.note);
      break;

    case "image":
    case "screenshot":
      if (!opts.file)
        throw new Error(`--file is required for --type ${opts.type}`);
      await ingestImage(
        opts.file,
        inv,
        opts.entityId,
        opts.contentId,
        opts.type as MediaType,
        opts.note,
      );
      break;

    case "text":
      if (!opts.entityId)
        throw new Error("--entity-id is required for --type text");
      if (!opts.text) throw new Error("--text is required for --type text");
      await ingestText(
        opts.entityId,
        opts.text,
        inv,
        "post" as ContentType,
        opts.lang as TextLang | undefined,
        undefined,
        opts.note,
      );
      break;

    case "profile":
      if (!opts.file) throw new Error("--file is required for --type profile");
      await ingestProfile(opts.file, inv);
      break;

    default:
      program.help();
  }
}

run()
  .catch((err: Error) => {
    console.error(err.message);
    process.exitCode = 1;
  })
  .finally(() => closePool());
