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

const readJson = (cwd, name) => {
  try {
    return JSON.parse(fs.readFileSync(path.join(cwd, name), 'utf8'));
  } catch {
    return null;
  }
};
const truncate = (value, limit) =>
  String(value ?? '')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, limit);
const detectStack = (manifest, pkg) => {
  const explicit = manifest?.stack ?? manifest?.techStack ?? manifest?.project?.stack;
  if (explicit) return Array.isArray(explicit) ? explicit.join(', ') : String(explicit);
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
  const found = [];
  if (pkg) found.push('Node.js');
  if (deps.react) found.push('React');
  if (deps.vue) found.push('Vue');
  if (deps.next) found.push('Next.js');
  if (deps.express) found.push('Express');
  if (deps.fastify) found.push('Fastify');
  if (deps['@nestjs/core']) found.push('NestJS');
  return found.join(', ');
};

/** Injects compact project metadata into every subagent start. */
export const subagentContext = async (context) => {
  if (context.event !== 'SubagentStart') return { decision: 'allow' };
  const manifest = readJson(context.cwd, '.aikit-scaffold.json');
  const pkg = readJson(context.cwd, 'package.json');
  if (!manifest && !pkg) return { decision: 'allow' };
  const conventions =
    manifest?.conventions ?? manifest?.keyConventions ?? manifest?.project?.conventions;
  const conventionText = Array.isArray(conventions)
    ? conventions.slice(0, 3).join('; ')
    : conventions;
  const name = truncate(pkg?.name ?? manifest?.name ?? path.basename(context.cwd), 60);
  const description = truncate(
    pkg?.description ?? manifest?.description ?? manifest?.project?.description,
    120,
  );
  const stack = truncate(detectStack(manifest, pkg) || 'unknown', 80);
  const contextText = [
    `Project: ${name}${description ? ` — ${description}` : ''}`,
    `Stack: ${stack}`,
    `Conventions: ${truncate(conventionText || 'Reuse existing scaffold patterns.', 120)}`,
    'Use aikit search/file_summary/compact — NOT raw read_file for understanding code.',
  ].join('\n');
  return { additionalContext: contextText };
};

createHook(subagentContext);
