import { Command } from 'commander';
import { callDaemon } from '../client/http-client.js';
import { formatOutput } from '../output/formatter.js';

export function registerInteractionCommands(program: Command) {
  program
    .command('click <ref>')
    .description('拟人化点击元素（含 actionability 检查：visible + scrollIntoView）')
    .requiredOption('--session <name>')
    .option('--mode <mode>', 'full|fast|off')
    .option('--raw')
    .action(async (ref, opts) => {
      const mode = opts.mode ?? process.env.NETA_BROWSER_HUMANIZE_MODE ?? 'full';
      await callDaemon('/admin/browser-daemon/click', { sessionName: opts.session, ref, mode });
      console.log(formatOutput({ clicked: ref }, opts.raw));
    });

  program
    .command('hover <ref>')
    .description('拟人化悬停（触发下拉菜单等 hover 事件场景）')
    .requiredOption('--session <name>')
    .option('--mode <mode>', 'full|fast|off')
    .option('--raw')
    .action(async (ref, opts) => {
      const mode = opts.mode ?? process.env.NETA_BROWSER_HUMANIZE_MODE ?? 'full';
      await callDaemon('/admin/browser-daemon/hover', { sessionName: opts.session, ref, mode });
      console.log(formatOutput({ hovered: ref }, opts.raw));
    });

  program
    .command('fill <ref> <value>')
    .description('拟人化填写输入框（自动 focus + clear + 拟人化 type）')
    .requiredOption('--session <name>')
    .option('--mode <mode>')
    .option('--raw')
    .action(async (ref, value, opts) => {
      const mode = opts.mode ?? process.env.NETA_BROWSER_HUMANIZE_MODE ?? 'full';
      await callDaemon('/admin/browser-daemon/fill', { sessionName: opts.session, ref, value, mode });
      console.log(formatOutput({ filled: ref }, opts.raw));
    });

  program
    .command('type <text>')
    .description('在已 focused 输入框拟人化输入文本')
    .requiredOption('--session <name>')
    .option('--mode <mode>')
    .option('--raw')
    .action(async (text, opts) => {
      const mode = opts.mode ?? process.env.NETA_BROWSER_HUMANIZE_MODE ?? 'full';
      await callDaemon('/admin/browser-daemon/type', { sessionName: opts.session, text, mode });
      console.log(formatOutput({ typed: text.length }, opts.raw));
    });

  program
    .command('select <ref> <value>')
    .description('选择 <select> 元素的某个 option（value 可逗号分隔多选）')
    .requiredOption('--session <name>')
    .option('--raw')
    .action(async (ref, value, opts) => {
      const v = value.includes(',') ? value.split(',').map((s: string) => s.trim()) : value;
      const r = await callDaemon('/admin/browser-daemon/select-option', { sessionName: opts.session, ref, value: v });
      console.log(formatOutput(r, opts.raw));
    });

  program
    .command('check <ref>')
    .description('勾选复选框（用 --uncheck 反向操作）')
    .requiredOption('--session <name>')
    .option('--uncheck', '取消勾选')
    .option('--raw')
    .action(async (ref, opts) => {
      await callDaemon('/admin/browser-daemon/check', { sessionName: opts.session, ref, checked: !opts.uncheck });
      console.log(formatOutput({ ref, checked: !opts.uncheck }, opts.raw));
    });

  program
    .command('press <key>')
    .description('按键（如 Enter、Tab、Escape、Control+A）')
    .requiredOption('--session <name>')
    .option('--raw')
    .action(async (key, opts) => {
      await callDaemon('/admin/browser-daemon/press-key', { sessionName: opts.session, key });
      console.log(formatOutput({ pressed: key }, opts.raw));
    });

  program
    .command('scroll <deltaY>')
    .description('滚动页面（正数向下，负数向上，单位 px）')
    .requiredOption('--session <name>')
    .option('--mode <mode>', 'full|fast|off')
    .option('--raw')
    .action(async (deltaY, opts) => {
      const mode = opts.mode ?? process.env.NETA_BROWSER_HUMANIZE_MODE ?? 'full';
      await callDaemon('/admin/browser-daemon/scroll', { sessionName: opts.session, deltaY: parseInt(deltaY, 10), mode });
      console.log(formatOutput({ scrolled: deltaY }, opts.raw));
    });

  program
    .command('wait')
    .description('等待元素状态或页面 loadState')
    .requiredOption('--session <name>')
    .option('--ref <ref>', '等待某个元素')
    .option('--state <state>', 'visible|hidden|attached|detached', 'visible')
    .option('--load-state <s>', 'load|domcontentloaded|networkidle')
    .option('--timeout <ms>', '超时（毫秒）', parseInt)
    .option('--raw')
    .action(async (opts) => {
      const dto: any = { sessionName: opts.session };
      if (opts.ref) dto.ref = opts.ref;
      if (opts.state) dto.state = opts.state;
      if (opts.loadState) dto.loadState = opts.loadState;
      if (opts.timeout) dto.timeout = opts.timeout;
      await callDaemon('/admin/browser-daemon/wait-for', dto);
      console.log(formatOutput({ ok: true }, opts.raw));
    });

  program
    .command('screenshot')
    .description('截图返回 base64（或保存到 --out 指定的文件）')
    .requiredOption('--session <name>')
    .option('--full-page', '截整页（含视口外）')
    .option('--out <path>', '保存到文件')
    .option('--raw')
    .action(async (opts) => {
      const r: any = await callDaemon('/admin/browser-daemon/screenshot', { sessionName: opts.session, fullPage: !!opts.fullPage });
      if (opts.out) {
        const fs = await import('node:fs/promises');
        await fs.writeFile(opts.out, Buffer.from(r.base64, 'base64'));
        console.log(formatOutput({ saved: opts.out, bytes: r.base64.length }, opts.raw));
      } else {
        console.log(formatOutput(r, opts.raw));
      }
    });

  program
    .command('eval <script>')
    .description('在页面执行 JS 表达式，返回结果（仅诊断用，反风控敏感场景慎用）')
    .requiredOption('--session <name>')
    .option('--raw')
    .action(async (script, opts) => {
      const r = await callDaemon('/admin/browser-daemon/eval', { sessionName: opts.session, script });
      console.log(formatOutput(r, opts.raw));
    });
}
