import { readdirSync, readFileSync, writeFileSync } from 'fs';
import { join, dirname, basename, isAbsolute, resolve } from 'path';
import { fileURLToPath } from 'url';

const args = process.argv.slice(2);
const widthArg = args.find(a => /^\d+$/.test(a));
const fileArg = args.find(a => a.endsWith('.md') || a.endsWith('.txt'));
const WIDTH = parseInt(widthArg, 10) || 70;
const scriptDir = dirname(fileURLToPath(import.meta.url));
const workflowsDir = join(scriptDir, '..', 'workflows');
const promptsDir = join(scriptDir, '..', 'source', 'prompts');

function wrapParagraph(text) {
  const words = text.split(/\s+/);
  const lines = [];
  let line = '';
  for (const word of words) {
    if (!line) {
      line = word;
    } else if (line.length + 1 + word.length <= WIDTH) {
      line += ' ' + word;
    } else {
      lines.push(line);
      line = word;
    }
  }
  if (line) lines.push(line);
  return lines.join('\n');
}

function wrapBody(body) {
  return body.split('\n\n').map(block => {
    if (block.startsWith('- ') || block.startsWith('  ') || block.includes('\n- ')) {
      return block.split('\n').map(line => {
        if (line.length <= WIDTH) return line;
        const match = line.match(/^(\s*-\s*)/);
        if (!match) return wrapParagraph(line);
        const prefix = match[1];
        const rest = line.slice(prefix.length);
        const indent = ' '.repeat(prefix.length);
        const words = rest.split(/\s+/);
        const lines = [];
        let cur = '';
        for (const word of words) {
          if (!cur) {
            cur = word;
          } else if (prefix.length + cur.length + 1 + word.length <= WIDTH) {
            cur += ' ' + word;
          } else {
            lines.push(cur);
            cur = word;
          }
        }
        if (cur) lines.push(cur);
        return lines.map((l, i) => (i === 0 ? prefix : indent) + l).join('\n');
      }).join('\n');
    }
    return wrapParagraph(block);
  }).join('\n\n');
}

function resolveFileArg(arg) {
  if (isAbsolute(arg)) return resolve(arg);
  if (arg.includes('/')) return resolve(arg);
  if (arg.endsWith('.txt')) return join(promptsDir, arg);
  return join(workflowsDir, arg);
}

const filePaths = fileArg
  ? [resolveFileArg(fileArg)]
  : [
    ...readdirSync(workflowsDir).map(f => join(workflowsDir, f)).filter(f => f.endsWith('.md')),
    ...readdirSync(promptsDir).map(f => join(promptsDir, f)).filter(f => f.endsWith('.txt')),
  ];

for (const filePath of filePaths) {
  const name = basename(filePath);
  const content = readFileSync(filePath, 'utf-8');
  const isTxt = filePath.endsWith('.txt');

  const fmMatch = content.match(/^---\n([\s\S]*?)\n---\n/);
  if (!isTxt && !fmMatch) {
    console.log(`${name}: no frontmatter, skipping`);
    continue;
  }

  const frontmatter = fmMatch ? fmMatch[0] : '';
  const body = content.slice(frontmatter.length);
  const wrapped = wrapBody(body.trimEnd());

  const result = frontmatter + wrapped + '\n';
  if (result === content) {
    console.log(`${name}: already wrapped`);
  } else {
    writeFileSync(filePath, result);
    console.log(`${name}: rewrapped to ${WIDTH} columns`);
  }
}
