#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { createHook } from './_runtime.mjs';

const exists = (cwd, name) => {
  try {
    return fs.existsSync(path.join(cwd, name));
  } catch {
    return false;
  }
};
const list = (cwd) => {
  try {
    return fs.readdirSync(cwd);
  } catch {
    return [];
  }
};
const readJson = (cwd, name) => {
  try {
    return JSON.parse(fs.readFileSync(path.join(cwd, name), 'utf8'));
  } catch {
    return null;
  }
};
const detectPackageManager = (cwd, pkg) =>
  pkg?.packageManager?.split('@')[0] ||
  (exists(cwd, 'pnpm-lock.yaml') && 'pnpm') ||
  (exists(cwd, 'yarn.lock') && 'yarn') ||
  ((exists(cwd, 'bun.lockb') || exists(cwd, 'bun.lock')) && 'bun') ||
  (exists(cwd, 'package-lock.json') && 'npm') ||
  'unknown';

/** Detects workspace metadata and injects stack context at session start. */
export const sessionInit = async (context) => {
  if (context.event !== 'SessionStart') return { decision: 'allow' };
  const pkg = readJson(context.cwd, 'package.json');
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
  const entries = list(context.cwd);
  const framework = deps.react
    ? 'React'
    : deps.vue
      ? 'Vue'
      : deps.angular
        ? 'Angular'
        : deps.next
          ? 'Next.js'
          : deps.express
            ? 'Express'
            : deps.fastify
              ? 'Fastify'
              : '';
  const stack = pkg
    ? `Node.js${framework ? `, ${framework}` : ''}`
    : exists(context.cwd, 'go.mod')
      ? 'Go'
      : exists(context.cwd, 'Cargo.toml')
        ? 'Rust'
        : exists(context.cwd, 'requirements.txt') || exists(context.cwd, 'pyproject.toml')
          ? 'Python'
          : entries.some((name) => /\.(sln|csproj)$/i.test(name))
            ? '.NET'
            : exists(context.cwd, 'pom.xml') || exists(context.cwd, 'build.gradle')
              ? 'Java/Kotlin'
              : 'Unknown';
  const monorepo = exists(context.cwd, 'pnpm-workspace.yaml')
    ? 'yes (pnpm-workspace)'
    : exists(context.cwd, 'lerna.json')
      ? 'yes (lerna)'
      : exists(context.cwd, 'packages')
        ? 'yes (packages/)'
        : 'no';
  const metadata = [
    `Workspace: ${path.basename(context.cwd)}`,
    `Stack: ${stack}`,
    `Monorepo: ${monorepo}`,
    `Package manager: ${detectPackageManager(context.cwd, pkg)}`,
    ...(pkg ? [`Node: ${process.version}`] : []),
  ].join('\n');
  return { additionalContext: metadata };
};

createHook(sessionInit);
