// Set to true to re-enable the /sub coding agent
const SUB_ENABLED = false;

import type { Context } from 'telegraf';
import { runClaudeCLI } from '../agent/runner.js';
import { createStreamingReply } from '../agent/chunker.js';
import { escapeMarkdown } from '../utils/format.js';
import { logger } from '../utils/logger.js';

export interface SubHandlerOptions {
  claudeBin: string;
  repoPath: string;
  timeoutMs: number;
}

export function makeSubHandler(opts: SubHandlerOptions) {
  return async function subHandler(ctx: Context): Promise<void> {
    if (!SUB_ENABLED) {
      await ctx.reply('⚙️ /sub is currently disabled.');
      return;
    }

    const text = ctx.message && 'text' in ctx.message ? ctx.message.text : '';
    const task = text.replace(/^\/sub\s*/i, '').trim();

    if (!task) {
      await ctx.reply('Usage: /sub <coding task>\nExample: /sub add a mobile variant to DealCard');
      return;
    }

    logger.debug('sub command received', { taskLen: task.length });

    const placeholder = `⏳ Claude is working on:\n_${escapeMarkdown(task)}_`;
    const finalize = await createStreamingReply(ctx, placeholder);

    let accumulated = '';

    try {
      await runClaudeCLI(task, {
        ...opts,
        onChunk: (chunk) => {
          accumulated += chunk;
        },
      });

      const result = accumulated.trim() || '_(Claude returned no output)_';
      await finalize(result);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      await finalize(`❌ *Claude error:*\n\`\`\`\n${msg.slice(0, 500)}\n\`\`\``);
    }
  };
}
