#!/usr/bin/env node
// Apply sealseek 喜豆 cost passthrough to @mariozechner/pi-ai after npm install.
//
// Reason: sealclaw's chat path goes through pi-coding-agent -> pi-agent-core ->
// @mariozechner/pi-ai (all dynamically imported, not bundled). pnpm honors
// `pnpm.patchedDependencies` to patch the installed pi-ai, but npm does not.
// Without this script, npm-installed sealclaw runs unpatched pi-ai, and the
// upstream `usage.cost` number (喜豆) never reaches the UI.
//
// npm typically hoists `@mariozechner/pi-ai` to the top-level node_modules, not
// inside sealclaw/node_modules, so we resolve via createRequire to find the
// real install location.
//
// Idempotent: skips silently if already patched, missing, or in an unexpected
// shape. Must never fail the install.

import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, parse } from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

function resolveTarget() {
  // pi-ai's `exports` only defines the `import` condition (no `require`), so
  // createRequire(...).resolve("@mariozechner/pi-ai") throws
  // ERR_PACKAGE_PATH_NOT_EXPORTED. Walk parent directories looking for the
  // installed file directly — same algorithm Node uses to find node_modules.
  const REL = "node_modules/@mariozechner/pi-ai/dist/providers/openai-completions.js";
  let dir = __dirname;
  const { root } = parse(dir);
  while (true) {
    const candidate = join(dir, REL);
    if (existsSync(candidate)) {
      return candidate;
    }
    if (dir === root) {
      return null;
    }
    dir = dirname(dir);
  }
}

const MARKER = "PATCH(sealseek)";
const ANCHOR = "calculateCost(model, usage);\n    return usage;\n}";
const REPLACEMENT = `calculateCost(model, usage);
    // PATCH(sealseek): 上游若直接在 usage 里给了 cost 数字（喜豆），优先采用它作为 total
    if (typeof rawUsage.cost === "number" && Number.isFinite(rawUsage.cost) && rawUsage.cost > 0) {
        usage.cost.total = rawUsage.cost;
    }
    return usage;
}`;

try {
  const target = resolveTarget();
  if (!target || !existsSync(target)) {
    console.warn(
      "[postinstall-patch-pi-ai] @mariozechner/pi-ai not resolvable from this package; skipping",
    );
    process.exit(0);
  }
  const src = readFileSync(target, "utf8");
  if (src.includes(MARKER)) {
    process.exit(0);
  }
  if (!src.includes(ANCHOR)) {
    console.warn(
      `[postinstall-patch-pi-ai] anchor not found in ${target}; pi-ai shape changed, skipping patch`,
    );
    process.exit(0);
  }
  const patched = src.replace(ANCHOR, REPLACEMENT);
  writeFileSync(target, patched);
  console.log(`[postinstall-patch-pi-ai] applied sealseek 喜豆 cost patch to ${target}`);
} catch (err) {
  console.warn(`[postinstall-patch-pi-ai] skipped: ${err?.message ?? err}`);
}
