#!/usr/bin/env node
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const here = dirname(fileURLToPath(import.meta.url));
const arg = (name) => {
  const index = process.argv.indexOf(`--${name}`);
  return index >= 0 ? process.argv[index + 1] : null;
};
const fail = (message) => {
  process.stderr.write(`${message}\n`);
  process.exit(1);
};

const project = arg('project');
const workspace = arg('workspace');
const toolsRoot = arg('tools-root');
const baseUrl = (arg('base-url') || process.env.KITTYCLAW_BASE_URL || 'http://localhost:5230').replace(/\/$/, '');
if (!project || !workspace || !toolsRoot) {
  fail('Usage: node install-workflow.mjs --project <slug> --workspace <path> --tools-root <yt-community-publisher-path> [--base-url <url>]');
}

for (const script of ['yt-validate-processor.mjs', 'yt-post-processor.mjs', 'yt-submit.mjs']) {
  if (!existsSync(resolve(toolsRoot, '.agents', 'tools', script))) fail(`Missing publisher tool: ${script}`);
}

const request = async (path, options = {}) => {
  const response = await fetch(`${baseUrl}${path}`, options);
  if (!response.ok) fail(`${options.method || 'GET'} ${path} failed: HTTP ${response.status} ${await response.text()}`);
  return response.status === 204 ? null : response.json();
};
const jsonOptions = (method, body) => ({
  method,
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(body)
});

await request(`/api/projects/${encodeURIComponent(project)}`);
const definition = JSON.parse(readFileSync(resolve(here, 'workflow.example.json'), 'utf8'));
const existingColumns = await request(`/api/projects/${encodeURIComponent(project)}/columns`);
for (const column of definition.columns) {
  if (!existingColumns.some((item) => item.name === column.name)) {
    await request(`/api/projects/${encodeURIComponent(project)}/columns`, jsonOptions('POST', column));
  }
}

const automationsPath = resolve(workspace, '.agents', 'automations.json');
mkdirSync(dirname(automationsPath), { recursive: true });
const current = existsSync(automationsPath)
  ? JSON.parse(readFileSync(automationsPath, 'utf8'))
  : { automations: [] };
const postsDir = resolve(workspace, 'posts');
mkdirSync(postsDir, { recursive: true });
const replacements = {
  '{{TOOLS_ROOT}}': resolve(toolsRoot).replaceAll('\\', '/'),
  '{{PROJECT}}': project,
  '{{POSTS_DIR}}': postsDir.replaceAll('\\', '/')
};
let renderedText = JSON.stringify(definition.automations);
for (const [token, value] of Object.entries(replacements)) renderedText = renderedText.replaceAll(token, value);
const rendered = JSON.parse(renderedText);
const ids = new Set(rendered.map((item) => item.id));
current.automations = [...(current.automations || []).filter((item) => !ids.has(item.id)), ...rendered];
writeFileSync(automationsPath, `${JSON.stringify(current, null, 2)}\n`);

const submitEnvironment = { YT_BOARD_PROJECT: project, YT_POSTS_DIR: postsDir };
process.stdout.write(`${JSON.stringify({ project, columns: definition.columns.map((item) => item.name), automations: rendered.map((item) => item.id), automationsPath, submitEnvironment })}\n`);
