#!/usr/bin/env node

import { existsSync } from "node:fs";
import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { OwnerEvidenceToolsAdapter, ownerEvidenceToolPolicy } from "../src/adapters/ownerEvidenceTools.js";
import { LinkedInToolsAdapter } from "../src/adapters/linkedinTools.js";
import { ScraplingAdapter } from "../src/adapters/scrapling.js";
import { GoogleMapsScrapperAdapter } from "../src/adapters/googleMapsScrapper.js";

const rootDir = process.cwd();
const run = await loadRun(argValue("--runId") || argValue("--run-id") || "current");
const scrapling = new ScraplingAdapter({ rootDir });
const output = {
  ok: true,
  recheck: process.argv.includes("--recheck"),
  rootDir,
  tools: {
    googleMapsScrapper: new GoogleMapsScrapperAdapter({ rootDir, storage: { rawDir: path.join(rootDir, "data", "raw") } }).available(),
    scraplingEnricher: scrapling.available(),
    ownerEvidenceToolkit: new OwnerEvidenceToolsAdapter({ rootDir }).available(),
    ownerProfileTools: new LinkedInToolsAdapter({ rootDir, scrapling }).available()
  },
  scripts: {
    ownerEvidenceTools: existsSync(path.join(rootDir, "tools", "hermes_owner_evidence_tools.py")),
    scraplingEnrich: existsSync(path.join(rootDir, "tools", "hermes_scrapling_enrich.py")),
    linkedinProfileApi: existsSync(path.join(rootDir, "tools", "hermes_linkedin_profile_api.mjs"))
  },
  latestRunEvidence: {
    id: run.id || "",
    status: run.status || "",
    updatedAt: run.updatedAt || "",
    ownerEvidenceToolAttemptCount: Array.isArray(run.ownerEvidenceToolAttempts) ? run.ownerEvidenceToolAttempts.length : 0
  },
  ownerEvidenceToolPolicy: {
    website: ownerEvidenceToolPolicy(run, { mode: "website" }),
    profiles: ownerEvidenceToolPolicy(run, { mode: "profiles" })
  }
};

output.ok = Boolean(
  output.tools.googleMapsScrapper &&
  output.tools.scraplingEnricher &&
  output.tools.ownerEvidenceToolkit?.ok &&
  output.tools.ownerProfileTools?.ok
);

console.log(JSON.stringify(output, null, 2));

function argValue(name) {
  const direct = process.argv.find((arg) => arg.startsWith(`${name}=`));
  if (direct) return direct.slice(name.length + 1);
  const index = process.argv.indexOf(name);
  return index >= 0 ? process.argv[index + 1] || "" : "";
}

async function loadRun(id) {
  const runsDir = path.join(rootDir, "data", "runs");
  if (id && id !== "current") {
    return JSON.parse(await readFile(path.join(runsDir, `${id}.json`), "utf8"));
  }
  try {
    const files = (await readdir(runsDir)).filter((file) => file.endsWith(".json"));
    const runs = [];
    for (const file of files) {
      try {
        runs.push(JSON.parse(await readFile(path.join(runsDir, file), "utf8")));
      } catch {
        continue;
      }
    }
    runs.sort((a, b) => String(b.updatedAt || b.createdAt).localeCompare(String(a.updatedAt || a.createdAt)));
    return runs.find((item) => ["queued", "running"].includes(item.status)) || runs[0] || {};
  } catch {
    return {};
  }
}
