#!/usr/bin/env node
/* eslint-env node */
"use strict";

const fs = require("node:fs");
const path = require("node:path");

// Skip in CI — install logs are noisy and the warning won't be acted on.
if (process.env.CI) process.exit(0);

// Skip when developing this package itself: pnpm/npm set INIT_CWD to the
// consumer's project root. If it matches our own package root, we're being
// installed by our own `pnpm install`, not by a downstream app.
const packageRoot = path.resolve(__dirname, "..");
const initCwd = process.env.INIT_CWD;
if (!initCwd || initCwd === packageRoot) process.exit(0);

// Idempotency: only warn on first install. The marker lives inside this
// package's own node_modules directory, so it's wiped on `rm -rf node_modules`
// (which is when the consumer most needs a reminder).
const marker = path.join(packageRoot, ".install-warned");
if (fs.existsSync(marker)) process.exit(0);

const hooks = require("./hooks-with-deps.json");
const exampleHooks = hooks.slice(0, 3).join(", ") + (hooks.length > 3 ? ", ..." : "");

const message = `
╭──────────────────────────────────────────────────────────────────────╮
│  @yaoc1996/js-tools — Enable ESLint validation                        │
│                                                                       │
│  This package exposes custom React hooks with deps arrays            │
│  (${exampleHooks.padEnd(64)}) │
│  Extend our shipped ESLint config so \`exhaustive-deps\` and           │
│  \`no-unused-deps\` validate them in your code.                        │
│                                                                       │
│  Flat config — eslint.config.js (ESLint 9+):                          │
│    import jsTools from "@yaoc1996/js-tools/eslint";                  │
│    export default [jsTools, /* your config */];                      │
│                                                                       │
│  Suppress this message:                                              │
│    touch node_modules/@yaoc1996/js-tools/.install-warned             │
╰──────────────────────────────────────────────────────────────────────╯
`;

// Write to stderr so it shows alongside install output regardless of stdout
// buffering. Postinstall scripts often have stdout suppressed by package
// managers in non-verbose mode; stderr is more reliable.
process.stderr.write(message);

try {
    fs.writeFileSync(marker, new Date().toISOString());
} catch {
    // Read-only node_modules (Docker, some CI setups) — ignore.
}
