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

export function registerSessionCommands(program: Command) {
  program
    .command('open <url>')
    .description('启动会话并打开 URL')
    .requiredOption('--session <name>', 'session 名称')
    .option('--proxy <url>', '代理 URL（http://user:pass@host:port）')
    .option('--fingerprint-seed <n>', '指纹 seed', parseInt)
    .option('--profile-dir <name>', 'profile 目录名')
    .option('--headed', '有头模式')
    .option('--priority <p>', 'low|normal|high', 'normal')
    .option('--queue', '排队等位')
    .option('--raw', '输出 raw JSON')
    .action(async (url, opts) => {
      const dto: any = {
        sessionName: opts.session,
        url,
        priority: opts.priority,
        queue: !!opts.queue,
        headed: !!opts.headed,
      };
      if (opts.fingerprintSeed != null) dto.fingerprintSeed = opts.fingerprintSeed;
      if (opts.profileDir) dto.profileDir = opts.profileDir;
      if (opts.proxy) dto.proxy = parseProxyUrl(opts.proxy);
      const r = await callDaemon('/admin/browser-daemon/open', dto);
      console.log(formatOutput(r, opts.raw));
    });

  program
    .command('close')
    .description('关闭会话')
    .requiredOption('--session <name>')
    .option('--raw')
    .action(async (opts) => {
      await callDaemon('/admin/browser-daemon/close', { sessionName: opts.session });
      console.log(formatOutput({ ok: true }, opts.raw));
    });

  program
    .command('list')
    .description('列出所有会话')
    .option('--raw')
    .action(async (opts) => {
      const r = await callDaemonGet('/admin/browser-daemon/list');
      console.log(formatOutput(r, opts.raw));
    });
}

function parseProxyUrl(url: string) {
  const u = new URL(url);
  return {
    server: `${u.protocol}//${u.host}`,
    username: decodeURIComponent(u.username) || undefined,
    password: decodeURIComponent(u.password) || undefined,
  };
}
