#!/usr/bin/env node
import { createRequire } from "node:module";
import path from "node:path";

const payload = await readStdinJson();
const vendorDir = payload.vendorDir || path.join(process.cwd(), "tools", "vendor", "linkedin-profile-scraper-api");
const sessionCookieValue = payload.sessionCookieValue || process.env.HERMES_LINKEDIN_LI_AT || "";

if (!payload.url) finish({ ok: false, error: "missing LinkedIn profile URL" });
if (!sessionCookieValue) finish({ ok: false, skipped: true, error: "missing HERMES_LINKEDIN_LI_AT" });

try {
  const requireFromVendor = createRequire(path.join(vendorDir, "package.json"));
  const { LinkedInProfileScraper } = requireFromVendor("linkedin-profile-scraper");
  const scraper = new LinkedInProfileScraper({
    sessionCookieValue,
    keepAlive: false,
    timeout: Number(payload.timeout || 30000)
  });
  await scraper.setup();
  const profile = await scraper.run(payload.url);
  await scraper.close();
  const text = JSON.stringify(profile || {});
  finish({
    ok: true,
    profile,
    emails: extractEmails(text),
    phones: extractPhones(text),
    text
  });
} catch (error) {
  finish({ ok: false, error: error.message || String(error) });
}

function readStdinJson() {
  return new Promise((resolve) => {
    let input = "";
    process.stdin.setEncoding("utf8");
    process.stdin.on("data", (chunk) => { input += chunk; });
    process.stdin.on("end", () => {
      try {
        resolve(JSON.parse(input || "{}"));
      } catch {
        resolve({});
      }
    });
  });
}

function extractEmails(text) {
  return [...new Set(String(text || "").match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi) || [])];
}

function extractPhones(text) {
  return [...new Set(String(text || "").match(/(?:\+?1[\s.-]?)?(?:\(?\d{3}\)?[\s.-]?)\d{3}[\s.-]?\d{4}/g) || [])];
}

function finish(result) {
  process.stdout.write(`${JSON.stringify(result)}\n`);
  process.exit(result.ok || result.skipped ? 0 : 1);
}
