import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import YAML from 'yaml';
import { AgentDefinitionSchema, AgentTaskSchema } from '../src/agent/schemas.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PACKAGE_ROOT = path.resolve(__dirname, '..');
const DEFINITIONS_DIR = path.resolve(PACKAGE_ROOT, 'src/agent/definitions');
const PROMPTS_DIR = path.resolve(PACKAGE_ROOT, 'src/agent/prompts');
const OUTPUT_PATH = path.resolve(PACKAGE_ROOT, 'src/agent/definitions.generated.ts');

function readText(filePath: string): string {
  return fs.readFileSync(filePath, 'utf-8');
}

function main(): void {
  const agentDefinition = AgentDefinitionSchema.parse(
    YAML.parse(readText(path.join(DEFINITIONS_DIR, 'agent.yaml'))),
  );

  const tasksDir = path.join(DEFINITIONS_DIR, 'tasks');
  const taskFiles = fs.readdirSync(tasksDir)
    .filter((file) => file.endsWith('.yaml'))
    .sort();
  const tasks = taskFiles.map((file) =>
    AgentTaskSchema.parse(YAML.parse(readText(path.join(tasksDir, file)))),
  );

  const prompts = Object.fromEntries(
    fs.readdirSync(PROMPTS_DIR)
      .filter((file) => file.endsWith('.md'))
      .sort()
      .map((file) => [file, readText(path.join(PROMPTS_DIR, file)).trim()]),
  );

  const output = `// AUTO-GENERATED by scripts/gen-agent-definitions.ts — DO NOT EDIT.
// Run \`npm run codegen\` to regenerate.
//
// Bundled agent definition assets for the Bun-compiled binary path.
// The compiled binary resolves loader paths under \`/$bunfs/\`, where the
// source YAML files are not readable from the real filesystem. The loader
// falls back to these parsed definitions and prompt templates in that case.

import type { AgentDefinition, AgentTask } from './types.js';

export const BUNDLED_AGENT_DEFINITION: AgentDefinition = ${JSON.stringify(agentDefinition, null, 2)} as const;

export const BUNDLED_AGENT_TASKS: readonly AgentTask[] = ${JSON.stringify(tasks, null, 2)} as const;

export const BUNDLED_AGENT_PROMPTS: Readonly<Record<string, string>> = ${JSON.stringify(prompts, null, 2)} as const;
`;

  fs.writeFileSync(OUTPUT_PATH, output);
  process.stdout.write(
    `[gen-agent-definitions] wrote ${path.relative(PACKAGE_ROOT, OUTPUT_PATH)} (${taskFiles.length} tasks, ${Object.keys(prompts).length} prompts)\n`,
  );
}

main();
