import path from "node:path";
import { fileURLToPath } from "node:url";
import { HermesAgent } from "../src/hermes.js";
import { leadsCsv, leadExportFilename } from "../src/export.js";
import { Storage } from "../src/storage.js";
import { loadEnv } from "../src/utils.js";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, "..");

loadEnv(path.join(rootDir, ".env"));

const storage = new Storage(path.join(rootDir, "data"));
await storage.init();

const agent = new HermesAgent({
  projectName: path.basename(rootDir),
  rootDir,
  storage
});

const platform = process.argv[2] || "google_maps";
const reposPerPlatform = Number(process.argv[3] || 8);

console.log("=== GitHub Owners pilot ===");
console.log(`platform = ${platform}`);
console.log(`reposPerPlatform = ${reposPerPlatform}`);

const run = await agent.startRun({
  source: "github-owners",
  platforms: [platform],
  reposPerPlatform,
  target: 5,
  minScore: 50,
  minStars: 0
});

console.log(`run id = ${run.id}`);

let attempts = 0;
let finalRun;
while (attempts < 120) {
  await new Promise((r) => setTimeout(r, 2000));
  finalRun = await storage.getRun(run.id);
  attempts += 1;
  if (["complete", "failed", "cancelled", "killed", "partial", "interrupted"].includes(finalRun?.status)) {
    break;
  }
}

console.log(`status = ${finalRun?.status}`);
console.log(`qualified = ${finalRun?.qualifiedLeads?.length || 0}`);
console.log(`discovered = ${finalRun?.counters?.ownersHunted || 0}`);
console.log(`keptHunting = ${finalRun?.counters?.ownersKeptHunting || 0}`);
console.log(`repos processed = ${finalRun?.counters?.reposProcessed || 0}`);
console.log(`repos accepted = ${finalRun?.counters?.reposAccepted || 0}`);
console.log(`diagnosis: ${finalRun?.diagnosis}`);

console.log("\n=== Hunt log (first 8 entries) ===");
for (const entry of (finalRun?.huntLog || []).slice(0, 8)) {
  console.log(`- ${entry.owner} | repo=${entry.repo} | angles=${entry.angles.join(", ")} | emails=${entry.emails.length} phones=${entry.phones.length} hasSummary=${Boolean(entry.summary?.summary)}`);
}

console.log("\n=== Qualified leads ===");
for (const lead of (finalRun?.qualifiedLeads || [])) {
  console.log(`- ${lead.name} (${lead.login || ""}) | email=${lead.email} | phone=${lead.phone} | score=${lead.quality?.score}`);
  console.log(`  repo: ${lead.repoFullName} (${lead.repoStars} stars, ${lead.repoLanguage})`);
  console.log(`  summary: ${lead.summary}`);
  console.log(`  angles: ${(lead.angles || []).join(", ")}`);
}

const csv = leadsCsv(finalRun);
const filename = leadExportFilename(finalRun);
const outPath = path.join(rootDir, "data", "raw", filename);
await import("node:fs/promises").then((fs) => fs.writeFile(outPath, csv));
console.log(`\nCSV written: ${outPath}`);
console.log(`CSV preview:\n${csv.split("\n").slice(0, 8).join("\n")}`);
