import fs from "node:fs";
import path from "node:path";

const defaultDocsRoot = path.resolve(
  "..",
  "hadron-docs",
  "mintlify-community-docs-hadron-b51558d4-42980fb81f44b42bf15e2700307712514f6640c5",
);

const docsRoot = process.env.MINTLIFY_LOCAL_DOCS_ROOT
  ? path.resolve(process.env.MINTLIFY_LOCAL_DOCS_ROOT)
  : defaultDocsRoot;

const generatedApi = path.resolve("target/doc-md/hadron_sdk");
const outApi = path.join(docsRoot, "sdk", "rust", "reference", "api");

function rmrf(target) {
  fs.rmSync(target, { recursive: true, force: true });
}

function copyDir(from, to) {
  fs.mkdirSync(to, { recursive: true });
  for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
    const src = path.join(from, entry.name);
    const dst = path.join(to, entry.name);
    if (entry.isDirectory()) copyDir(src, dst);
    else if (entry.isFile()) fs.copyFileSync(src, dst);
  }
}

if (!fs.existsSync(docsRoot)) {
  console.error(`Mintlify docs root not found: ${docsRoot}`);
  console.error(
    "Set MINTLIFY_LOCAL_DOCS_ROOT to your docs root if it differs.",
  );
  process.exit(1);
}

if (!fs.existsSync(generatedApi)) {
  console.error(
    "Missing processed docs. Run `./scripts/generate-docs.sh` first.",
  );
  process.exit(1);
}

// Copy hand-written pages into place
const manualPages = [
  "sdk/rust/quickstart.mdx",
  "sdk/rust/reference/pool-functions.mdx",
];
for (const rel of manualPages) {
  const src = path.resolve("mintlify-pages", rel);
  const dst = path.join(docsRoot, rel);
  if (fs.existsSync(src)) {
    fs.mkdirSync(path.dirname(dst), { recursive: true });
    fs.copyFileSync(src, dst);
  }
}

// Sync generated API docs
rmrf(outApi);
copyDir(generatedApi, outApi);

console.log(`Synced Rust SDK docs into: ${path.join(docsRoot, "sdk", "rust")}`);
